Ansi to Unicode Saveas

S

slachevsky

I Have a Ansi txt File
I need to save it as a Unicode File into a Script using and Ole Object
I Can open it, modify it and save it but i don't know how to change
the encoding
Thanks
 
K

Karl E. Peterson

I Have a Ansi txt File
I need to save it as a Unicode File into a Script using and Ole Object
I Can open it, modify it and save it but i don't know how to change
the encoding

VB(A) Strings are Unicode naturally. If Word's object model doesn't provide a
direct SaveAs in this format, just write the file directly using binary i/o...

Public Function WriteFileU(ByVal FileName As String, ByVal Data As String) As
Boolean
Dim hFile As Long
Dim uData() As Byte

' Convert String data to Unicode bytes.
uData = Data

' Since this is binary, we need to delete existing crud.
On Error Resume Next
Kill FileName

' Okay, now we just spit out what was given.
On Error GoTo Hell
hFile = FreeFile
Open FileName For Binary As #hFile
Put #hFile, , uData
Close #hFile
Hell:
WriteFileU = Not CBool(Err.Number)
End Function
 
K

Klaus Linke

You could also add a "byte order mark", so Word and other apps can determine
it's a Unicode text file automatically:

' Convert String data to Unicode bytes.
uData = ChrW(&HFEFF) & Data

Regards,
Klaus
 
K

Karl E. Peterson

Klaus Linke said:
You could also add a "byte order mark", so Word and other apps can determine
it's a Unicode text file automatically:

Good suggestion! I modified that library routine to this:

Public Function WriteFileU(ByVal FileName As String, ByVal Data As String,
Optional ByVal ByteOrderMark As Boolean = True) As Boolean
Dim hFile As Long
Dim uData() As Byte

' Since this is binary, we need to delete existing crud.
On Error Resume Next
Kill FileName

' Okay, now we just spit out what was given.
On Error GoTo Hell
hFile = FreeFile
Open FileName For Binary As #hFile
If ByteOrderMark Then
' Indicate to other apps that this is Unicode text.
' http://en.wikipedia.org/wiki/Byte_Order_Mark
uData = ChrW$(&HFEFF)
Put #hFile, , uData
End If
' Convert String data to Unicode bytes.
uData = Data
Put #hFile, , uData
Close #hFile
Hell:
WriteFileU = Not CBool(Err.Number)
End Function

Thanks... Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top