You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB Excel宏合并CSV文件时日文内容乱码,求代码排查修复

CSV追加日文内容乱码问题排查

编写了一段VB Excel宏用于合并两个CSV文件,但遇到问题:原有CSV文件包含日文文本,执行代码后,新生成的CSV文件中追加的内容出现乱码。

原代码

Sub Append2CSV()
    Dim tmpCSV As String 'string to hold the CSV info
    Dim f As Integer
    Dim csvFile As String
    Set data_sheet = ThisWorkbook.Worksheets("Test")
   
    LastColumnCell = data_sheet.Cells(Rows.Count, "A").End(xlUp).row
    csvFile = Range("E3").Value
    f = FreeFile
    
    Open csvFile For Append As #f
        tmpCSV = Range2CSV(Range("A5:CZ" & LastColumnCell))
    Print #f, tmpCSV
    Close #f
    
    MsgBox "Test Data is appended in the Static Resource succesfully.", vbOKOnly, "Static Resource Update"
    
End Sub

Function Range2CSV(list As Range) As String
    
    Dim data As Variant
    Dim r As Long, c As Long
    Dim csvRecord As String, csvEmptyFields As String
    Dim csvAll As String
    
    csvAll = ""
    
    data = list.Value
    For r = 1 To UBound(data)
        csvEmptyFields = ""
        csvRecord = ""
        For c = 1 To UBound(data, 2)
            If Not IsEmpty(data(r, c)) Then
                csvRecord = csvRecord & csvEmptyFields & data(r, c) & ","
                csvEmptyFields = ""
            Else
                csvEmptyFields = csvEmptyFields & ","
            End If
        Next
        If csvRecord <> "" Then csvAll = csvAll & Left(csvRecord, Len(csvRecord) - 1) & vbLf
    Next

    Range2CSV = Left(csvAll, Len(csvAll) - 1)
    
End Function

问题说明

原有CSV中的日文(红线标注)显示正常,但通过宏追加的内容(蓝线标注)出现乱码。

已尝试的方法(仍未解决)

尝试使用ADODB.Stream处理编码,但乱码问题依旧:

Open csvFile For Append As #f
        tmpCSV = Range2CSV(Range("A5:CZ" & LastColumnCell))
        
        On Error GoTo errHandler
        Dim fsT As Object
        Dim tFilePath As String
        tFilePath = csvFile + ".csv"
        
        Set fsT = CreateObject("ADODB.Stream")
        fsT.Type = 2 'Specify stream type - we want To save text/string data.
        fsT.Charset = "utf-8" 'Specify charset For the source text data.
        fsT.Open 'Open the stream And write binary data To the object
        fsT.WriteText tmpCSV
        fsT.SaveToFile tFilePath, 2 'Save binary data To disk
errHandler:
    Close #f

内容的提问来源于stack exchange,提问作者Suomynona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:10:24