【发布时间】:2019-03-01 14:49:45
【问题描述】:
使用 Excel 2016,我已经在 Excel 中打开了一个名为“Abc-123.csv”的 csv 文件,所以现在我有一张包含 csv 的表格。 我想使用 Data > From Text/CSV 再次打开 同一文件 (ActiveWorkbook) 并使用 encoding 1252: Western European (Windows)
我录制了一个宏,然后将其更改为一个函数,以便它可以接收外部 csv 文件。
我需要帮助使这个宏在我的 csv 名称不同的情况下更通用
Function Data_CSV(CSVFile)
ActiveWorkbook.Queries.Add Name:="Abc-123", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(File.Contents(""C:\CSV\Abc-123.csv""),[Delimiter="","", Columns=43, Encoding=1252, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & " #""Promoted Headers"" = Table.PromoteHeaders(Source, [PromoteAllScalars=true])," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(#""Promoted Headers"",{{""Sales Record Number"", Int64.Type}, {""User" & _
" Id"", type text}, {""Buyer Fullname"", type text}, {""Buyer Phone Number"", type text}, {""Buyer Email"", type text}, {""Buyer Address 1"", type text}, {""Buyer Address 2"", type text}, {""Buyer City"", type text}, {""Buyer State"", type text}, {""Buyer Zip"", type text}, {""Buyer Country"", type text}, {""Order ID"", type number}, {""Item ID"", type number}, {""Tr" & _
"ansaction ID"", type number}, {""Item Title"", type text}, {""Quantity"", Int64.Type}, {""Sale Price"", type text}, {""Shipping And Handling"", type text}, {""Sales Tax"", type text}, {""Insurance"", type text}, {""eBay Collected Tax"", type text}, {""Total Price"", type text}, {""Payment Method"", type text}, {""PayPal Transaction ID"", type text}, {""Sale Date"", " & _
"type date}, {""Checkout Date"", type date}, {""Paid on Date"", type date}, {""Shipped on Date"", type date}, {""Shipping Service"", type text}, {""Feedback Left"", type text}, {""Feedback Received"", type text}, {""Notes to Yourself"", type text}, {""Custom Label"", type text}, {""Listed On"", type text}, {""Sold On"", type text}, {""Private Notes"", type text}, {""" & _
"Product ID Type"", type text}, {""Product ID Value"", type text}, {""Product ID Value 2"", type text}, {""Variation Details"", type text}, {""Product Reference ID"", type text}, {""Tracking Number"", type text}, {""Phone"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Abc-123;Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Abc-123]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Abc_123"
.Refresh BackgroundQuery:=False
End With
End Function
【问题讨论】: