简体   繁体   English

使用VBA将多个CSV文件导入Excel中的多个工作表中

[英]Importing multiple CSV files into multiple worksheets in Excel using VBA

I am working to create a VBA/macro that imports 2 CSV files from a specific folder into 2 worksheets in an Excel template that I have created. 我正在创建一个VBA /宏,该VBA /宏可以将特定文件夹中的2个CSV文件导入到我创建的Excel模板的2个工作表中。

To be more specific, these files are created and saved as new workbooks on a daily basis (two new files being added into the folder everyday) so my problem is how to code my macro to always import the 2 latest files? 更具体地说,这些文件每天创建并保存为新工作簿(每天将两个新文件添加到该文件夹​​中),所以我的问题是如何对宏进行编码以始终导入两个最新文件?

Please see below the code from which I manually select and import the latest files using macro. 请在下面查看我使用宏手动选择和导入最新文件的代码。 However, re-running the macro does not work as it shows "run-time error '5' - invalid procedure call or argument" . 但是,重新运行宏不起作用,因为它显示“运行时错误'5'-无效的过程调用或参数” Your help would be much appreciated. 您的帮助将不胜感激。

Sub Macro1()
'
' Macro1 Macro
' IMPORT CSV FILES
'

'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;P:\APS\Reports_From_PDP\AP_PDP_VehicleLoad_Report_AM 19-01-2018 3-15-03 AM.csv" _
        , Destination:=Range("$A$1"))
        .CommandType = 0
        .Name = "AP_PDP_VehicleLoad_Report_AM 19-01-2018 3-15-03 AM"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Sheets.Add After:=ActiveSheet
    Application.CutCopyMode = False
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;P:\APS\Reports_From_PDP\AP_PDP_VehicleLoad_Report_PM 19-01-2018 7-15-02 PM.csv" _
        , Destination:=Range("$A$1"))
        .CommandType = 0
        .Name = "AP_PDP_VehicleLoad_Report_PM 19-01-2018 7-15-02 PM"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    Sheets("Sheet1").Select
    Columns("A:N").Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Range("A1").Select
    Sheets("Sheet2").Select
    Columns("A:N").Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Range("A1").Select
    Sheets("Sheet2").Select
    Sheets("Sheet2").Name = "PM"
    Sheets("Sheet1").Select
    Sheets("Sheet1").Name = "AM"
    Sheets("AM").Select
End Sub

You can find the latest file(s) this way: 您可以通过以下方式找到最新文件:

EDIT: Dir return only the filename, so you need to append the path, too. 编辑:目录仅返回文件名,因此您也需要附加路径。

EDIT2: As per user request a few Debug.Print is inserted. EDIT2:根据用户请求,插入了一些Debug.Print。

Sub main()
    Dim s1 as String, s2 as String

    s1 = LastFile("P:\APS\Reports_From_PDP\AP_PDP_VehicleLoad_Report_AM")
    Debug.Print "Last file1: " & s1
    s2 = LastFile("P:\APS\Reports_From_PDP\AP_PDP_VehicleLoad_Report_PM")
    Debug.Print "Last file2: " & s2
End Sub
Function LastFile(sName as String) as String
    Dim dLatest as Date
    Dim dFound as Date      ' date of one matching filename
    Dim sLatest as string   ' the latest file or ""
    Dim sFound as string    ' one matching filename
    Dim sPath as string

    dLatest = 0
    sLatest = vbnullstring
    sPath = Left$(sName,  InStrRev(sName, "\"))

    sFound = Dir(sName & "*.csv")
    Do While sFound <> vbnullstring
         Debug.Print "Found: " & sFound
         dFound = FileDateTime(sPath & sFound)
         If dFound > dLatest Then 
             dLatest = dFound
             sLatest = sFound
         Endif
         sFound = Dir
    Loop
    LastFile = sLatest
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM