I made a macro that generate a .csv file with datas from an excel sheet. When I click on a button, this csv file is send to a server and is consummed after minutes.
It works perfectly.
The only problem is that this csv file is generated in UTF-8 with BOM and I don't want that, I need UTF-8 without BOM
I got inspired from this function that I found simply and easy to read : Use "ADODB.Stream" to convert ANSI to UTF-8, miss 1-2 character in the first row
I tried to adapt it into this :
Function ConvertToUtf8(myFileIn, myFileOut)
Dim stream, strText
Set stream = CreateObject("ADODB.Stream")
stream.Type = 2 'text
stream.Charset = "_autodetect_all"
stream.Open
stream.LoadFromFile myFileIn
strText = stream.ReadText
stream.Close
stream.Type = 2
stream.Charset = "utf-8"
stream.Open
stream.Position = 3 'without BOM (doesn't work)
stream.WriteText strText
stream.SaveToFile myFileOut, 2
stream.Close
Set stream = Nothing
End Function
I don't know why but it creates the file into UTF-8 without BOM but this error pop-up :
(https://i.stack.imgur.com/Kbua4.jpg)
I'm pretty sure I'm not far from the solution but I don't find it
When I click on "debug", this line is in cause :
stream.Position = 3 'without BOM (doesn't work)
EDIT
Finally I found exactly what I was looking for, instead of a function which convert the file, a more efficient function to write directly in UTF-8 without BOM in the file :
Function WriteUTF8WithoutBOM(chaine As String, nomfichier As String)
Dim UTFStream As Object, BinaryStream As Object
With CreateObject("adodb.stream")
.Type = 2
.Mode = 3
.Charset = "UTF-8"
.LineSeparator = -1
.Open
.WriteText chaine, 1
.Position = 3 'skip BOM
Set BinaryStream = CreateObject("adodb.stream")
BinaryStream.Type = 1
BinaryStream.Mode = 3
BinaryStream.Open
'Strips BOM (first 3 bytes)
.CopyTo BinaryStream
.Flush
.Close
End With
BinaryStream.SaveToFile nomfichier, 2
BinaryStream.Flush
BinaryStream.Close
End Function
For the credit, I found it here https://www.excel-downloads.com/threads/question-de-conversion-en-utf-8-pour-une-vba-qui-enregistre-un-txt.20011510/ (Staple1600 answer)