【问题标题】:Open CSV data with encoding使用编码打开 CSV 数据
【发布时间】: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

【问题讨论】:

    标签: excel vba csv encoding


    【解决方案1】:

    Macro Setup Picture

    我真的更喜欢子程序而不是函数来导入数据,但如果你需要的话,适应一个函数应该不会太难。

    首先创建 3 个命名范围:“FileName”、“SheetName”和“Extension”。 然后将此代码粘贴到您正在使用的代码上。 如果您经常这样做,我建议您在电子表格中添加一个按钮。

    这适用于许多文本文件类型(.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
    

    希望这会有所帮助! :)

    【讨论】:

    • 哇,这非常精巧和有用,但我认为它错过了应该以 1252 编码打开文件的部分,我的主要目标是读取重音字符。有什么建议吗?
    • 我提醒我想再次打开 ActiveWorkbook 但已编码(这使得获取文件名、路径和扩展名更容易)
    • 嗨,Assaf,很抱歉我花了一段时间才回复这个问题。事实证明,我们需要做的就是将上面宏中的“850”更改为 1252 - 哇!它现在应该可以工作了。如果还有什么我可以帮忙的,请告诉我。干杯!
    猜你喜欢
    • 2016-12-09
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多