How can I import a month of csv files (date named) into Excel via VBA?

后端 未结 2 986
情深已故
情深已故 2021-01-22 06:59

I need to load a month of CSV files into Excel for analysis via VBA. Each day of the month is a separate file with the date name (YYYYMMDD).

Currently, I can load two f

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-22 07:28

    have you condidered using ADODB and the ODBC Text File Driver / Jet 4.0 to retrieve your data into recordsets, then dump them into worksheets:

    dim cN as new adodb.connection
    dim rS as new adodb.recordset
    dim sDate as string
    dim sDataPath as string
    
    sDataPath="C:\Data"
    sdate=date ' maybe loop through date arrary, or list of dates in sheet?
    
    with cN
        .CursorLocation = 3 ' adUseClient 
        .CursorType = 3 ' adopenstatic
        .LockType = 1 ' adLockReadOnly         
        .Open ("Provider=Microsoft.Jet.OLEDB.4.0;" & _
               "Data Source=" & sDataPath & ";" & _
               "Extended Properties=""text; HDR=Yes; FMT=Delimited; IMEX=1;""")
    end with 
    
    with RS
        .ActiveConnection = cN
        .Source = "select * from data_" & sdate & "_.csv"
        .open
    end with
    
    range("A1").copyfromrecordset rs
    

    so put your csv files in the path defined the variable sDataPath, set the date variable sDate (maybe within a loop) and start testing!

    for more info on this type pf technique, here is the original MSDN article by Scripting Clinic (in the good old days):

    MSDN: Much ADO about Text Files

    Plus you'll fine a veritable plethora of information on the net using Google:)

提交回复
热议问题