Unicode string for flat file from vba

I want to save a unicode string in a flat file in a window window from an excel / vba macro. The macro converts the normal string to a Unicode representation, you must save it in a file and get it later.

+3
source share
3 answers

As already mentioned, you can use Microsoft Scripting Runtime Runtime (scrrun.dll). I have given some examples below. Some people also like the IO functions of their own file. There is an extensive (and rather complete) topic here: http://www.xtremevbtalk.com/showthread.php?t=123814

However, for Unicode files, this is perhaps the least painful to use Textstreams :)

Public Sub StringToTextFile(ByVal path As String, ByVal value As String)
    'Requires reference to scrrun.dll
    Dim fso As Scripting.FileSystemObject
    Dim ts As Scripting.TextStream
    Set fso = New Scripting.FileSystemObject
    Set ts = fso.CreateTextFile(path, False, True)
    ts.Write value
    ts.Close
End Sub

Public Sub LazyMansWay(ByVal path As String, ByVal value As String)
    'Reference counting will cause the objects to be destroyed. The termination
    'events of the classes will cause the connections to be closed.
    CreateObject("Scripting.FileSystemObject").CreateTextFile(path, False, True).Write value
End Sub
+5
source

COM- Microsoft Scripting Runtime (scrrun.dll).

( , FileSystemObject/TextStream) // .

+2

The best solution I could see is to read a string into a byte array and write each byte to a binary

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 by opening the file in binary mode and reading each byte into an array of bytes, 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
+1
source

Source: https://habr.com/ru/post/1710819/


All Articles