1

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)

SachaCS
  • 11
  • 1
  • 4
  • Look https://stackoverflow.com/questions/31435662/vba-save-a-file-with-utf-8-without-bom . IT is two stages: one you create a stream with BOM. Then you put your position to 3 (so after BOM). Second step: you copy from that stream. Because you start from byte 3, you will not copy BOM. Your error: you are moving to position 3 before you have 3 bytes on the file. – Giacomo Catenazzi Jan 23 '19 at 16:56
  • Show the error you get as copyable, searchable text in the body of the question. –  Jan 23 '19 at 17:43
  • 1
    I finally found what I wanted, but thks for the help ;) – SachaCS Jan 23 '19 at 17:45

0 Answers0