该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
2011-11-08
vba 读写文件,utf-8编码格式
2010-07-28 22:33 780人阅读 评论(0) 收藏 举报
这是一个转换UTF-8格式文本文件的示例,包括读取和写入,需要用到两个API函数:MultiByteToWideChar和WideCharToMultiByte
。
Public Declare Function MultiByteToWideChar Lib "kernel32" ( _
ByVal CodePage As Long, _
ByVal dwFlags As Long, _
ByRef lpMultiByteStr As Any, _
ByVal cchMultiByte As Long, _
ByVal lpWideCharStr As Long, _
ByVal cchWideChar As Long) As Long
Public Declare Function WideCharToMultiByte Lib "kernel32" ( _
ByVal CodePage As Long, _
ByVal dwFlags As Long, _
ByVal lpWideCharStr As Long, _
ByVal cchWideChar As Long, _
ByRef lpMultiByteStr As Any, _
ByVal cchMultiByte As Long, _
ByVal lpDefaultChar As String, _
ByVal lpUsedDefaultChar As Long) As Long
Public Const CP_UTF8 = 65001
' 将输入文本写进UTF8格式的文本文件
' 输入
' strInput:文本字符串
' strFile:保存的UTF8格式文件路径
' bBOM:True表示文件带"EFBBBF"头,False表示不带
Sub WriteUTF8File(strInput As String, strFile As String, Optional bBOM As Boolean = True)
Dim bByte As Byte
Dim ReturnByte() As Byte
Dim lngBufferSize As Long
Dim lngResult As Long
Dim TLen As Long
' 判断输入字符串是否为空
If Len(strInput) = 0 Then Exit Sub
On Error GoTo errHandle
' 判断文件是否存在,如存在则删除
If Dir(strFile) <> "" Then Kill strFile
TLen = Len(strInput)
lngBufferSize = TLen * 3 + 1
ReDim ReturnByte(lngBufferSize - 1)
lngResult = WideCharToMultiByte(CP_UTF8, 0, StrPtr(strInput), TLen, _
ReturnByte(0), lngBufferSize, vbNullString, 0)
If lngResult Then
lngResult = lngResult - 1
ReDim Preserve ReturnByte(lngResult)
Open strFile For Binary As #1
If bBOM = True Then
bByte = 239
Put #1, , bByte
bByte = 187
Put #1, , bByte
bByte = 191
Put #1, , bByte
End If
Put #1, , ReturnByte
Close #1
End