1

我想使用 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"

我认为问题在于这部分:

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

我尝试了几种变体,但都没有奏效。有人可以帮我解决这个问题吗?

谢谢!

4

1 回答 1

0

再看一遍,我相信我找到了问题所在。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

于 2021-06-03T17:14:14.580 回答