使用Excel 2016,我已经在Excel中打开了一个名为“ Abc-123.csv”的csv文件,所以现在我有一张csv文件。 我想使用数据>来自文本/ CSV 再次打开同一文件(ActiveWorkbook),并使用编码1252:西欧(Windows) < / p>
我记录了一个宏,然后将其更改为一个函数,以便它可以接收外部的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
答案 0 :(得分:0)
我真的更喜欢子例程而不是函数来导入数据,但是如果您需要的话,适应函数应该不会太困难。
首先创建3个命名范围:“文件名”,“表名”和“扩展名”。 然后将此代码粘贴到您正在使用的代码上。 如果您经常这样做,建议您向电子表格中添加一个按钮。
这适用于许多文本文件类型(.csv,.txt等):
Sub LoadData()
'This subroutine will load data from text-formatted files without opening them.
Dim ThisWB As Workbook
Set ThisWB = ThisWorkbook
filename = Range("FileName").Value
SheetName = Range("SheetName").Value
extension = Range("Extension").Value
If extension = ".csv" Then
isCSV = True
Else
isCSV = False
End If
If (SheetExists(SheetName, ThisWB) = False) Then
Call createSheet(SheetName, ThisWB)
End If
Sheets(SheetName).Select
Sheets(SheetName).Cells(1, 1).Select
With ActiveSheet.QueryTables _
.Add(Connection:="TEXT;" & filename, Destination:=ActiveCell)
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = (Not (isCSV))
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = isCSV
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
ActiveSheet.QueryTables.Item(ActiveSheet.QueryTables.Count).Delete
End Sub
Function SheetExists(ByVal shtName As String, Optional WB As Workbook) As Boolean
'This subroutine will test to see if a worksheet already exists within a workbook
Dim sht As Worksheet
If WB Is Nothing Then Set WB = ThisWorkbook
On Error Resume Next
Set sht = WB.Sheets(shtName)
On Error GoTo 0
SheetExists = Not sht Is Nothing
End Function
Sub createSheet(ByVal shtName As String, WB As Workbook)
'This subroutine will create a sheet for the data to be imported to, if that sheet does not already exist.
Dim ws As Worksheet
With WB
Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
ws.Name = shtName
End With
End Sub
希望这会有所帮助! :)