问题
Is it possible to generate a UTF-8 file using Visual Basic (VBA) in Excel 2016 for Mac? I need to generate an XML or TXT file that is encoded.
Thanks
回答1:
Not UTF-8, but UTF-16 is what VBA uses internally, so you can dump string data directly:
Dim fnum As Integer
fnum = FreeFile()
Open "utf16.txt" For Binary Access Write As fnum
'write UTF-16 Byte Order Marker
'
Put #fnum, 1, &HFE
Put #fnum, 2, &HFF
printLineUtf16 fnum, "Olá Mundo!"
Close #fnum
Function printLineUtf16(fnum As Integer, str As String)
str = str & ChrW(10) 'append newline
Dim data() As Byte 'coerce string to bytes
data = str
Put #fnum, LOF(fnum) + 1, data 'append bytes to file
End Function
This should work in Excel Mac 2011 and 2016, and in Windows versions. Note that you won't be able to type Unicode string literals in the editor, just simple accented Latin letters like the "á" above, but strings assigned from the Value of a cell will be preserved in Unicode.
来源:https://stackoverflow.com/questions/41946262/mac-excel-generate-utf-8-using-vba