Whenever I have to write data into a text file following function has proven to fulfill my needs.
Source Code
In case you want to export a file in Unicode encoding you just hand True for the parameter isUtf16Le, which will cause the FileSystemObject to encode the file in UTF-16 with low byte order mark (little endian).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
' @Author - Alexander Bolte' @ChangeDate - 2014-10-08' @Description - Writes a given text as a new line into a text file available at given file path.' If target text file is not existing yet, it will be created before writing given String.' If target text file is existing already, given data will be appended.' @Param fileNam - target text file full path.' @Param newLine - String to append in given target text file.' @Param isUtf16Le - a boolean indicating if a text file should be Unicode (UTF-16-Little Endian) or ASCII encoded.' True means a file should be UTF-16 Little Endian encoded.PublicFunctionwriteLineToTextFile(ByValfileNamAsString,ByValnewLineAsString,ByValisUtf16LeAsBoolean)DimfsAsNewScripting.FileSystemObjectDimtsAsScripting.TextStreamIffs.FileExists(fileNam)ThenSetts=fs.OpenTextFile(fileNam,ForAppending,True,isUtf16Le)ElseSetts=fs.CreateTextFile(fileNam,True,isUtf16Le)EndIfIfNottsIsNothingThenCallts.WriteLine(newLine)EndIfts.CloseSetts=NothingSetfs=NothingEndFunction
If you however have to export something in UTF-8 or other encodings I suggest to use the following method.
It utilizes the ADODB API in order to create a UTF-8 encoded text stream. The byte order mark is removed from this stream before it is written into a file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
SubWriteUTF8WithoutBOM()DimUTFStreamAsObjectSetUTFStream=CreateObject("adodb.stream")UTFStream.Type=adTypeTextUTFStream.Mode=adModeReadWriteUTFStream.Charset="UTF-8"UTFStream.LineSeparator=adLFUTFStream.OpenUTFStream.WriteText"This is an unicode/UTF-8 test.",adWriteLineUTFStream.WriteText"First set of special characters: öäåñüûú€",adWriteLineUTFStream.WriteText"Second set of special characters: qwertzuiopõúasdfghjkléáûyxcvbnm\|Ä€Í÷×äðÐ[]í³£;?¤>#&@{}<;>*~¡^¢°²`ÿ´½¨¸0",adWriteLineUTFStream.Position=3'skip BOMDimBinaryStreamAsObjectSetBinaryStream=CreateObject("adodb.stream")BinaryStream.Type=adTypeBinaryBinaryStream.Mode=adModeReadWriteBinaryStream.Open'Strips BOM (first 3 bytes)UTFStream.CopyToBinaryStream'UTFStream.SaveToFile "d:\adodb-stream1.txt", adSaveCreateOverWriteUTFStream.FlushUTFStream.CloseBinaryStream.SaveToFile"C:\users\wjx130\upload\test_text_export_utf-8.txt",adSaveCreateOverWriteBinaryStream.FlushBinaryStream.CloseEndSub