使用 VBA 将 UTF-8 转换为 ANSI
Convert UTF-8 to ANSI using VBA
我有一个 VBA Excel 代码,它从 excel sheet 中获取日语数据,将其与文本文件中的日语数据进行比较,并将日语单词替换为英语单词。但我应该能够在 UTF-8 文本文件上执行此操作。此代码用奇怪的字符替换了所有日语单词。怎样保存才不会出问题?
Open sFileName For Input As iFileNum
For n = 1 To lngLastCell
Label5.Caption = n & "/" & lngLastCell
searchtext = MySearch(n)
valuetext = MyText(n)
eplcCount = 0
spltCount = 0
searchpart = Array(searchtext)
valuepart = Array(valuetext)
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum
sTemp = Replace(sTemp, searchtext, valuetext)
'iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Next n
代码适用于 ANSI 字符。
VBA 中的 Open
函数仅适用于 ANSI
编码文件和二进制文件。如果你想 read/write 一个 utf-8
文件,你必须找到另一种方法。
utf-8
编码的字符集比 ANSI
多,因此无法从 ANSI
无损地转换为 utf-8
。也就是说,Excel 和 VBA 中的 String
存储为 utf-16
(VBA 编辑器仍然使用 ANSI
),因此您只需要从 utf-8
转换为 utf-16
.
与ADODB.Stream
:
Public Function ReadFile(path As String, Optional CharSet As String = "utf-8")
Static obj As Object
If obj Is Nothing Then Set obj = VBA.CreateObject("ADODB.Stream")
obj.CharSet = CharSet
obj.Open
obj.LoadFromFile path
ReadFile = obj.ReadText()
obj.Close
End Function
Public Sub WriteFile(path As String, text As String, Optional CharSet As String = "utf-8")
Static obj As Object
If obj Is Nothing Then Set obj = VBA.CreateObject("ADODB.Stream")
obj.CharSet = CharSet
obj.Open
obj.WriteText text
obj.SaveToFile path
obj.Close
End Sub
我有一个 VBA Excel 代码,它从 excel sheet 中获取日语数据,将其与文本文件中的日语数据进行比较,并将日语单词替换为英语单词。但我应该能够在 UTF-8 文本文件上执行此操作。此代码用奇怪的字符替换了所有日语单词。怎样保存才不会出问题?
Open sFileName For Input As iFileNum
For n = 1 To lngLastCell
Label5.Caption = n & "/" & lngLastCell
searchtext = MySearch(n)
valuetext = MyText(n)
eplcCount = 0
spltCount = 0
searchpart = Array(searchtext)
valuepart = Array(valuetext)
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum
sTemp = Replace(sTemp, searchtext, valuetext)
'iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Next n
代码适用于 ANSI 字符。
VBA 中的 Open
函数仅适用于 ANSI
编码文件和二进制文件。如果你想 read/write 一个 utf-8
文件,你必须找到另一种方法。
utf-8
编码的字符集比 ANSI
多,因此无法从 ANSI
无损地转换为 utf-8
。也就是说,Excel 和 VBA 中的 String
存储为 utf-16
(VBA 编辑器仍然使用 ANSI
),因此您只需要从 utf-8
转换为 utf-16
.
与ADODB.Stream
:
Public Function ReadFile(path As String, Optional CharSet As String = "utf-8")
Static obj As Object
If obj Is Nothing Then Set obj = VBA.CreateObject("ADODB.Stream")
obj.CharSet = CharSet
obj.Open
obj.LoadFromFile path
ReadFile = obj.ReadText()
obj.Close
End Function
Public Sub WriteFile(path As String, text As String, Optional CharSet As String = "utf-8")
Static obj As Object
If obj Is Nothing Then Set obj = VBA.CreateObject("ADODB.Stream")
obj.CharSet = CharSet
obj.Open
obj.WriteText text
obj.SaveToFile path
obj.Close
End Sub