How to save a Unicode character to a text file

2019-01-27 06:56发布

This is in Word for MAC VBA. I want to save the Unicode character from a text box to text file. For example this character "⅛".

I use this code.

Dim N as Long
N = FreeFile
Dim strText as String
strText = Textbox1.Text 'This is what is in the textbox "⅛"
Open <file path> For Output As N 
     Print #N, strText
Close N

It does not save the Unicode character. I understand I have to change the text encoding format. How do I do that?

Likewise, how to read the text file with the Unicode format?

2条回答
ゆ 、 Hurt°
2楼-- · 2019-01-27 07:15

I hope this will fit VBA for Word on Mac as well, but on Windows I have the CreateTextFile method of the FileSystemObject (see MSDN doc). There I can define to create a unicode text file.

  Set fsObject = CreateObject("Scripting.FileSystemObject")
  Set xmlFile = fsObject.CreateTextFile("path/filename.txt", True, True) 'the second "true" forces a unicode file.

  xmlFile.write "YourUnicodeTextHere"
  xmlFile.close
查看更多
闹够了就滚
3楼-- · 2019-01-27 07:27

VBA can't code text in UTF-8 this way. Use ADODB - yes, for text, not for database.

'ensure reference is set to Microsoft ActiveX DataObjects library
'(the latest version of it) under "tools/references"
Sub AdoTest()
    Dim adoStream As ADODB.Stream

    Set adoStream = New ADODB.Stream

    'Unicode coding
    adoStream.Charset = "Unicode" 'or any string listed in registry HKEY_CLASSES_ROOT\MIME\Database\Charset

    'open sream
    adoStream.Open

    'write a text
    adoStream.WriteText "Text for testing: ěšč", StreamWriteEnum.stWriteLine

    'save to file
    adoStream.SaveToFile "D:\a\ado.txt"

    adoStream.Close
End Sub

Reading is simplier, see my answer here:

Unicode and UTF-8 with VBA

Edited: I've inserted complete example.

Edited 2: Added refernce to list of coding in the registry

查看更多
登录 后发表回答