第1个回答 推荐于2016-06-05
抱歉,你的消息今晚才看到,现补上。
分二步:
一、新建一个模块,复制下面代码:
Option Explicit
Private 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
Private Const CP_UTF8 = 65001
'读文件至变量
Function GetFile(Filename As String) As String
Dim i As Integer, S As String, BB() As Byte
If Dir(Filename) = "" Then Exit Function
i = FreeFile
ReDim BB(FileLen(Filename) - 1)
Open Filename For Binary As #i
Get #i, , BB
Close #i
S = BB
GetFile = S
End Function
'写入文件1
Public Function PutFile(Filename As String, txt As String)
If txt = "" Then Exit Function
If Dir(Filename) <> "" Then Kill Filename
Dim i As Integer, S As String, BB() As Byte
i = FreeFile
Open Filename For Binary As #i
Put #i, , txt
Close #i
End Function
Public Function UTF8_Encode(Filename As String) As Boolean
Dim i As Long
Dim TLen As Long
Dim lPtr As Long
Dim UTF16 As Long
Dim UTF8_EncodeLong As String
Dim strUnicode As String, S As String
If Dir(Filename) = "" Or Filename = "" Then Exit Function
strUnicode = GetFile(Filename)
strUnicode = StrConv(strUnicode, vbUnicode)
TLen = Len(strUnicode)
If TLen = 0 Then Exit Function
Dim lngBufferSize As Long
Dim lngResult As Long
Dim bytUtf8() As Byte
lngBufferSize = TLen * 3 + 1
ReDim bytUtf8(lngBufferSize - 1)
lngResult = WideCharToMultiByte(CP_UTF8, 0, StrPtr(strUnicode), _
TLen, bytUtf8(0), lngBufferSize, vbNullString, 0)
If lngResult Then
lngResult = lngResult - 1
ReDim Preserve bytUtf8(lngResult)
S = StrConv(bytUtf8, vbUnicode)
End If
PutFile Filename, S
UTF8_Encode = True
End Function
二、程序调用如下:
If UTF8_Encode("f:\temp\a.txt") Then
MsgBox ""文件转换成功!"
Else
MsgBox "文件转换失败!"
End If
注意:转换成功后的文件将被覆盖,直接变成UTF-8编码。本回答被提问者采纳
第2个回答 推荐于2018-03-30
Private Sub AnsiToUtf8 (FileName as String)
Dim b() As Byte, S As String
Dim ADO_Stream As Object
If Dir(FileName) = "" Then Exit Sub
ReDim b(FileLen(FileName))
Open FileName For Binary As #1
Get #1, , b
Close #1
S = StrConv(b, vbUnicode)
Set ADO_Stream = CreateObject("ADODB.Stream")
With ADO_Stream
.Type = 2
.Mode = 3
.Charset = "utf-8"
.open
.WriteText S
.SaveToFile FileName, 2
End With
Set ADO_Stream = Nothing
End Sub
参考资料:
http://zhidao.baidu.com/question/83609963.html?si=3本回答被网友采纳