【问题标题】:Importing multiple CSV files into multiple worksheets in Excel using VBA使用 VBA 将多个 CSV 文件导入 Excel 中的多个工作表
【发布时间】:2018-07-14 20:09:35
【问题描述】:

我正在创建一个 VBA/宏,将 2 个 CSV 文件从特定文件夹导入到我创建的 Excel 模板中的 2 个工作表中。

更具体地说,这些文件每天都会创建并保存为新工作簿(每天将两个新文件添加到文件夹中)所以我的问题是如何编写宏以始终导入 2 个最新文件?

请参阅下面的代码,我从中手动选择并使用宏导入最新文件。但是,重新运行宏不起作用,因为它显示“运行时错误'5' - 无效的过程调用或参数”。非常感谢您的帮助。

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

【问题讨论】:

  • 请通过编辑您的原始问题将您的代码移动到您的问题正文中。
  • 嗨艾伦,我已将代码添加回原始查询。对此感到抱歉。
  • 好多了。我没有给你答案,我只是将你的帖子作为新海报进行审核。

标签: vba excel csv-import


【解决方案1】:

您可以通过这种方式找到最新的文件:

编辑:Dir 仅返回文件名,因此您也需要附加路径。

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

【讨论】:

  • 您好 AcsErno,非常感谢您花时间解决我的问题。我试图在宏中插入这段代码并删除格式化部分,只是为了看看它是否可以先获取最新的文件。但是它并没有完全起作用,因为出现了 "Run-time error '53': File not found" 的错误。当我点击“调试”按钮时,模块突出显示以下代码“dFound = FileDateTime (sFound)。请协助。
  • 没错,看我的编辑。
  • 嗨 AcsErno,非常感谢您的帮助。但是,这一次在我创建了一个新模块并点击 F5 之后什么都没有发生(期望这个新代码能够完美地导入数据...... :( 不太确定实际问题是什么......
  • 当你 Debug.Print s1 时会发生什么?空表示在指定路径没有找到文件。
  • 嗨 AcsErno,对于迟到的回复,我深表歉意。老实说,我是这个 VBA/宏领域的新手,所以不太确定如何在上述编码中输入“Debug.Print s1”...
猜你喜欢
  • 1970-01-01
  • 2021-01-27
  • 2016-04-17
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
相关资源
最近更新 更多