Unicode string to flat file from vba

前端 未结 3 827
-上瘾入骨i
-上瘾入骨i 2021-01-20 03:08

I want to store a unicode string in a flat file on a windows box from an excel/vba macro. The macro converts normal string to unicode representation, need to store it in a f

3条回答
  •  终归单人心
    2021-01-20 03:42

    The best solution I could figure is read the string in to a byte array and write each byte to a binary file

    Private Function WriteBinaryFile(ByRef szData As String)
        Dim bytData() As Byte
        Dim lCount As Long
    
        bytData = szData
        Open PwdFileName For Binary As #1
            For lCount = LBound(bytData) To UBound(bytData)
                Put #1, , bytData(lCount)
            Next lCount
        Close #1
    End Function
    

    Read it back by opening the file in binary mode and reading each byte into a byte array and then converting it to a string.

    Sub ReadBinaryFile(ByRef gszData As String)
    Dim aryBytes() As Byte
    Dim bytInput As Byte
    Dim intFileNumber
    Dim intFilePos
    
    intFileNumber = FreeFile
    
    Open PwdFileName For Binary As #intFileNumber
    intFilePos = 1
    
    Do
        Get #intFileNumber, intFilePos, bytInput
        If EOF(intFileNumber) = True Then Exit Do
        ReDim Preserve aryBytes(intFilePos - 1)
        aryBytes(UBound(aryBytes)) = bytInput
        intFilePos = intFilePos + 1
    Loop While EOF(intFileNumber) = False
    Close #intFileNumber
    
    gszData = aryBytes
    End Sub
    

提交回复
热议问题