how can I write UTF-8 encoded strings to a textfile from vba, like
Dim fnum As Integer
fnum = FreeFile
Open "myfile.txt" For Output As fnum
Print #fnum, "special characters: äöüß" 'latin-1 or something by default
Close fnum
Is there some setting on Application level?
You can use CreateTextFile or OpenTextFile method, both have an attribute "unicode" usefull for encoding settings.
Example: Overwrite:
Example: Append:
See more on MSDN docs
I found the answer on the web:
Certainly not as I expected...
This writes a Byte Order Mark at the start of the file, which is unnecessary in a UTF-8 file and some applications (in my case, SAP) don't like it. Solution here: Can I export excel data with UTF-8 without BOM?
I looked into the answer from Máťa whose name hints at encoding qualifications and experience. The VBA docs say
CreateTextFile(filename, [overwrite [, unicode]])
creates a file "as a Unicode or ASCII file. The value is True if the file is created as a Unicode file; False if it's created as an ASCII file. If omitted, an ASCII file is assumed." It's fine that a file stores unicode characters, but in what encoding? Unencoded unicode can't be represented in a file.The VBA doc page for
OpenTextFile(filename[, iomode[, create[, format]]])
offers a third option for the format:Máťa passes -1 for this argument.
Judging from VB.NET documentation (not VBA but I think reflects realities about how underlying Windows OS represents unicode strings and echoes up into MS Office, I don't know) the system default is an encoding using 1 byte/unicode character using an ANSI code page for the locale.
UnicodeEncoding
is UTF-16. The docs also describe UTF-8 is also a "Unicode encoding," which makes sense to me. But I don't yet know how to specify UTF-8 for VBA output nor be confident that the data I write to disk with the OpenTextFile(,,,1) is UTF-16 encoded. Tamalek's post is helpful.Here is another way to do this - using the API function WideCharToMultiByte: