News, links, downloads, tips and tricks on Microsoft Access and related

About Me Search
Name:Alex Dybenko

Location:Moscow, Russia

Friday, June 01, 2007

How to write out Unicode text files in VBA

This trick I have learned from Giorgio Rancati, Access MVP. Here a sample code, which clearly explains the idea:

Dim buffer As String

Open "C:\Unicode.txt" For Binary As #1

buffer = StrConv(strText2Write, vbUnicode) + _

StrConv(vbCrLf, vbUnicode)

Put #1, , buffer

Close #1

Technorati tags: ,


Blogger Unknown said...

Internally, all VB strings are in Unicode format anyway. The "put" statement converts strings to ANSI *unless* you pass the string as a byte array.

The StrConv method that Giorgio provides will work but includes much extra (unnecessary) overhead because you're essentially converting the VB unicode string (2 bytes per character) to a 4-byte per character string thus using much more memory and requiring extra processing.

Here's the better way using the byte array mentioned above:

Sub WriteUnicodeTextFile(ByRef Path As String, _
ByRef Value As String)

Dim Buffer() As Byte
Dim FileNum As Integer

' Convert string to an array of bytes, preserving unicode (2bytes per character)
Buffer = Value

FileNum = FreeFile
Open Path For Binary As FileNum
Put FileNum, , Buffer
Close FileNum

End Sub

Wayne Phillips

12:37 PM  
Blogger Alex Dybenko said...

Thanks for update, Wayne!

12:41 PM  
Anonymous Anonymous said...

This worked a treat, thanks to you both.

12:33 PM  
Blogger Alex Dybenko said...

And one more - from Tony Jollans:
Set MyStream = CreateObject("ADODB.Stream")
With MyStream
.Type = adTypeText
.Charset = "Unicode"
.WriteText r!Captn ' your foreign unicode text
.SaveToFile "C:\whatever.txt"
End With

12:00 PM  
Anonymous dirtytyphon said...

Great job! Thanks!

1:07 PM  

Post a Comment

<< Home