Pages

Tuesday 20 March 2012

Writing Pure UTF-8 file in vba using ADODB.Stream

for appending to an existing file just send in myappend true...
Call WriteUTF8WithBOM(sometext, afile, true)
Public Function WriteUTF8WithBOM(mytext As Variant, myfullfilename As String, myappend As Boolean)
    Dim fsT As Object
    Set fsT = CreateObject("ADODB.Stream")
    fsT.Type = 2 'Specify stream type - we want To save text/string data.
    fsT.Charset = "utf-8" 'Specify charset For the source text data.
    fsT.Open 'Open the stream And write binary data To the object
        
        If myappend Then
            myx = ""
            fsT.LoadFromFile (myfullfilename)
            myx = fsT.ReadText(-1)
            'mytext = myx & mytext
        End If
    
    fsT.WriteText mytext
    
    fsT.SaveToFile myfullfilename, adSaveCreateOverWrite
    'fsT.SaveToFile sFileName, 2 'Save binary data To disk
End Function

Don't forget to add ActiveX Data Objects