Excel VBA - 导入使用 UTF 8 编码的文本文件



我正在使用以下代码将 TXT 文件导入我的 excel 工作簿,但是当数据包含中文/日语/韩语字符时遇到转换错误。

如何导入使用 UTF-8 编码的文本文件以确保字符正确显示?

' Set default path to pick files
    IntPath = ""
    Set pickf = Application.FileDialog(msoFileDialogFilePicker)
' Set detail options for selection window
    With pickf
        .InitialView = msoFileDialogViewDetails:
        .InitialFileName = IntPath:
        .Filters.Clear:
        .Filters.Add "Textfile", "*.txt", 1:
        .ButtonName = "Import":
        .Title = "Select textfile for import"
' if nothing selected, close
        If .Show = -1 Then
            project = .SelectedItems(1)
            Else: Exit Sub
        End If
    End With
' speed up, unhide all report sheets and clear content
    With ActiveWorkbook
        .Application.CutCopyMode = False
        .Application.DisplayAlerts = False
        .Application.ScreenUpdating = False
        .Application.EnableEvents = False
        .Application.Calculation = xlCalculationManual
    End With
' import textfile into temp sheet
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & project, Destination:=Sheets("Opera Data").Range("A2"))
        .PreserveFormatting = True
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .RefreshStyle = xlOverwriteCells
        .Refresh BackgroundQuery:=False
    End With

我正在导入csv文件,我也遇到了同样的问题,我刚刚通过定义解决了问题

 .TextFilePlatform = 65001 

像这样在这里

        .
        .
        .
' import textfile into temp sheet
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & project, Destination:=Sheets("Opera Data").Range("A2"))
        .PreserveFormatting = True
        .TextFilePlatform = 65001 ' here you can put here What characterset you want.
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .RefreshStyle = xlOverwriteCells
        .Refresh BackgroundQuery:=False
    End With

我也从这里拿走了这个。 它可能会有所帮助https://chandoo.org/forum/threads/open-csv-utf-8-files-no-acces-to-editing-bom.36165/

最新更新