本文主要是介绍00X集—vba代码将汉字用(utf-8)编码写入文本文档,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
以下代码尚有bug,需完善
Public Function StringToUtf8ByteArray(ByVal filePath As String, s As String) As Byte()
Dim i As Long, j As Long
Dim result() As Byte
Dim charCode As Integer
Dim bytesRequired As Integer
Dim char As String
' 初始化数组以容纳至少一个字符(单字节)
ReDim result(0)
' 遍历字符串中的每个字符
For i = 1 To Len(s)
char = Mid(s, i, 1) ' 获取单个字符
charCode = AscW(char)
' 根据字符的 Unicode 码点确定所需的字节数
If charCode < 128 Then
' 单字节字符
bytesRequired = 1
ElseIf charCode < 2048 Then
' 双字节字符
bytesRequired = 2
ElseIf charCode < 65536 Then
' 三字节字符
bytesRequired = 3
Else
' 不支持的字符(超出三字节范围)
MsgBox "字符串包含不支持的 UTF-8 字符。"
Exit Function
End If
' 如果当前数组空间不足,则扩展它
If UBound(result) + bytesRequired > i - 1 Then
If i = 1 Then
ReDim Preserve result(bytesRequired - 1)
Else
ReDim Preserve result(i + bytesRequired - 1)
End If
End If
' 将字符的 UTF-8 编码写入数组
' result(i + j - 1) = 0 ' 清除任何现有数据
Select Case bytesRequired
Case 1
result(i) = charCode
Case 2
result(i + 1) = 192 + (charCode \ 64)
result(i) = 128 + (charCode Mod 64)
Case 3
result(i + 1) = 224 + (charCode \ (64 * 64))
result(i) = 128 + ((charCode Mod (64 * 64)) \ 64)
result(i - 1) = 128 + (charCode Mod 64)
End Select
' 更新索引以反映已写入的字节数
' i = i + bytesRequired
Next i
' 重新定义数组大小以移除未使用的空间
' ReDim Preserve result(UBound(result) - (UBound(result) - i + 1))
'
' ' 返回字节数组
StringToUtf8ByteArray = result
End Function
' 将文本追加到 UTF-8 编码的文件中的子程序
Sub AppendTextToUtf8File()
Dim filePath As String
Dim fileNo As Integer
Dim textToAppend As String
Dim UTF8Bytes() As Byte
Dim i As Long
' 设置文件路径
filePath = "D:\ZD\1111.txt" ' 替换为你的文件路径
' 要追加的文本(汉字“你好”)
textToAppend = "大"
' 将文本转换为 UTF-8 字节数组
UTF8Bytes = StringToUtf8ByteArray(filePath, textToAppend)
' 以追加模式打开文件
fileNo = FreeFile()
Open filePath For Binary As #fileNo
' 写入 UTF-8 字节到文件
For i = LBound(UTF8Bytes) To UBound(UTF8Bytes)
Put #fileNo, 5, UTF8Bytes(i)
Next i
' 关闭文件
Close #fileNo
' 可选:显示消息框以确认操作
MsgBox "Text has been appended to the file."
End Sub
这篇关于00X集—vba代码将汉字用(utf-8)编码写入文本文档的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!