我想使用 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))
我尝试了几种变体,但都没有奏效。有人可以帮我解决这个问题吗?
谢谢!