Skip to content

Instantly share code, notes, and snippets.

@JoBrad
Last active December 14, 2023 10:30
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JoBrad/1023484 to your computer and use it in GitHub Desktop.
Save JoBrad/1023484 to your computer and use it in GitHub Desktop.
[VBA] Write a UTF-8 Encoded File
'Function saves cText in file, and returns 1 if successful, 0 if not
Public Function writeOut(cText As String, file As String) As Integer
On Error GoTo errHandler
Dim fsT As Object
Dim tFilePath As String
tFilePath = file + ".txt"
'Create Stream object
Set fsT = CreateObject("ADODB.Stream")
'Specify stream type - we want To save text/string data.
fsT.Type = 2
'Specify charset For the source text data.
fsT.CharSet = "utf-8"
'Open the stream And write binary data To the object
fsT.Open
fsT.writetext cText
'Save binary data To disk
fsT.SaveToFile tFilePath, 2
GoTo finish
errHandler:
MsgBox (Err.Description)
writeOut = 0
Exit Function
finish:
writeOut = 1
End Function
@AlexiaChen
Copy link

@sjzlei1989
Copy link

It works fine, thank you!

@Nomaxx
Copy link

Nomaxx commented Nov 21, 2019

Code works with one small correction:

Old:
Dim fsT, tFilePath As String

New
Dim fsT As Object
Dim tFilePath As String

Regards

@JoBrad
Copy link
Author

JoBrad commented Dec 2, 2019

@Nomaxx, updated. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment