如何将多个 csv 文件导入 Excel 中的查询连接?

How to import multiple csv files into querie connections in Excel?

我想使用 VBA 从 CSV 文件(它们具有相同的格式)导入数据 Excel 以使用查询循环导入数据和格式化。我的第一个目标是从所选文件夹中的文件创建连接。我有以下代码:

Sub ImportQueries()

Dim myPath As String
Dim myFile As Variant
Dim fileType As String
Dim i As Integer

 With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Select Source Folder"
        .AllowMultiSelect = False
        .Show

      myPath = .SelectedItems(1) & "\"
 End With
    
  fileType = "*.csv*"

  myFile = Dir(myPath & fileType)

  Do While myFile <> ""
  
ActiveWorkbook.Queries.Add Name:= _
        "Data" & i, Formula:= _
        "let" & Chr(13) & "" & Chr(10) & "    Source = Csv.Document(File.Contents(& myPath & myFile)),[Delimiter="";"", Columns=6, Encoding=1250, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Source,{{" & _
        """Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}, {""Column4"", type text}, {""Column5"", type text}, {""Column6"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Changed Type"""
   
    i = i + 1
    myFile = Dir
    
 Loop

MsgBox "Result Import Complete"
End Sub

执行宏后,我在 Excel 中的查询中收到以下消息:

Expression.Error: Token Literal expected.
Details:
    let
    Source = Csv.Document(File.Contents(& myPath & myFile)),[Delimiter=";", Columns=6, Encoding=1250, QuoteStyle=QuoteStyle.None]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}, {"Column2", type text}, {"Column3", type text}, {"Column4", type text}, {"Column5", type text}, {"Column6", type text}})
in
    #"Changed Type"

我认为问题出在这部分:

Source = Csv.Document(File.Contents(& myPath & myFile))

我尝试了几种变体,但其中 none 行得通。有人可以帮我解决这个问题吗?

谢谢!

再看一遍,我相信我找到了问题所在。 myFile 和 myPath 在引号内,使它们成为文字字符串“myFile”和“myPath”,而不是变量值 myFilemyPath.

为您的 Queries.Add 试试这个:

ActiveWorkbook.Queries.Add _
    Name:="Data" & i, _
    Formula:="let" & Chr(13) & Chr(10) & _
            "    Source = Csv.Document(File.Contents(""" & myPath & myFile & """),[Delimiter="";"", Columns=6, Encoding=1250, QuoteStyle=QuoteStyle.None])," & Chr(13) & Chr(10) & _
            "    #""Changed Type"" = Table.TransformColumnTypes(Source,{" & _
                                            "{""Column1"", type text}, " & _
                                            "{""Column2"", type text}, " & _
                                            "{""Column3"", type text}, " & _
                                            "{""Column4"", type text}, " & _
                                            "{""Column5"", type text}, " & _
                                            "{""Column6"", type text}" & _
                                    "})" & Chr(13) & Chr(10) & _
            "in" & Chr(13) & Chr(10) & _
            "    #""Changed Type"""

旁注:Chr(13) & Chr(10) 在 VBA、vbNewLine!

中有一个快捷方式