VBA: Make an .xml UTF-8 (2 byte) file

New_Alex
New_Alex used Ask the Experts™
on
Function SaveTextToFile(FileFullPath As String, _
 sText As String, Optional Overwrite As Boolean = False) As _
 Boolean
    
On Error GoTo ErrorHandler
Dim iFileNumber As Integer
iFileNumber = FreeFile

If Overwrite Then
    Open FileFullPath For Output As #iFileNumber
Else
    Open FileFullPath For Append As #iFileNumber
End If

Print #iFileNumber, sText
SaveTextToFile = True

ErrorHandler:
Close #iFileNumber
End Function

Open in new window


The above function saves the String contained in the variable  sText in the File given in the variable FileFullPath.

My problem is that my String contains also characters in other languages and I want to save it in a file with the extension .xml so it opens in Excel.

In the attached .zip file there are 2 files. "book1.xml" and "book2.xml".
book1.xml can be opened in an XML editor
book2.xml has been made using the aforementioned function and can not be opened in an XML editor since there is an encoding error
 
book1.xml is correct UTF-8
book2.xml made using the aforementioned function is defnitely saved as a one byte encoded file, and hex C5 et al. are illegal UTF-8, I am not sure it is ANSI, but it is a single byte encoding

Is it possible to make some modifications so the above mentioned function saves the multi-language string as an .xml UTF-8 (2 byte) file so it is compatible with other languages and opens with Excel or .xml editors?

Thank you.

The-xml-files.zip
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
you could try this :
Sub TestSaveTextToFile(FileFullPath As String, sText As String, Optional Overwrite As Boolean = False)

Dim stream As Object
Dim buffer As String

Set stream = CreateObject("ADODB.Stream")
stream.Type = 2 'Specify stream type - we want To save text/string data.
stream.Charset = "utf-8" 'Specify charset For the source text data.
stream.Open 'Open the stream And write binary data To the object

buffer = ""
If Not Overwrite Then
    stream.LoadFromFile FileFullPath
    buffer = stream.readtext
    stream.Position = 0
End If
stream.writetext = buffer & sText
stream.SaveToFile FileFullPath, 2
Set stream = Nothing

End Sub

Open in new window

Author

Commented:
WONDERFUL CODE BRO...

IT EVEN OVERWRITES THE FILE WHEN RUN TWICE !!!!!!!


THANK YOU !!!!!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial