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
相关产品推荐
相关产品推荐

