How to save a Unicode character to a text file

后端 未结 3 748
眼角桃花
眼角桃花 2020-12-20 02:22

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.

D         


        
3条回答
  •  长情又很酷
    2020-12-20 02:26

    The question is for VBA on Mac, and I'm afraid none of the answers work on a Mac.

    The question is about Unicode which comes in many flavours. I'll address the UTF-16 aspect of it. UTF-8 follows a different path, but it isn't difficult too. AFAIU, your question is about UTF-16 string.

    The code below has no error handling, I'll let you take care of that.

    Function writeUnicodeTextToFile(filePathName As String, myText As String)
    
    `Dim myFileNumber As Long, I As Long, byteArray() As Byte
    
    myFileNumber = FreeFile()
    Open filePathName For Binary As #myFileNumber
    
    ReDim byteArray(1)
    
    ' Create a BOM for your Unicode flavour
    ' (CHOOSE! one of the two, programmatically, or hard-code it)
     ' => Little Endian
        byteArray(0) = 255: byteArray(1) = 254
    ' => Big Endian
        'byteArray(0) = 254: byteArray(1) = 255
    
    ' now write the two-byte BOM
    Put myFileNumber, 1, byteArray
    
    ' redimension your byte array
    ' note it works even if you don't Redim (go figure) but it's more elegant
    I = (LenB(myText) / 2) - 1
    ReDim byteArray(I)
    
    ' populate the byte array...
    byteArray = myText
    
    ' ... and write you text AFTER the BOM
    Put myFileNumber, 3, byteArray
    Close #myFileNumber
    End Function
    

提交回复
热议问题