VBA函数将.csv转换为UTF-8,而无需BOM

时间:2019-01-23 15:15:46

标签: excel vba utf-8

我制作了一个宏,该宏使用Excel工作表中的数据生成一个.csv文件。 当我单击按钮时,此csv文件将发送到服务器,并在几分钟后被消耗。

它运行完美。

唯一的问题是,此csv文件是在带有BOM的UTF-8中生成的,我不希望那样,我需要没有BOM的UTF-8

我从此功能中获得启发,该功能简单易懂: Use "ADODB.Stream" to convert ANSI to UTF-8, miss 1-2 character in the first row

我试图将其调整为:

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

我不知道为什么,但是它在没有BOM的情况下将文件创建为UTF-8,但会弹出此错误:

https://imgur.com/a/FhJDAzh

我很确定我离解决方案不远,但是我找不到它

当我单击“调试”时,此行是有原因的:

stream.Position = 3 'without BOM (doesn't work)

编辑

最后,我找到了我想要的东西,而不是一个转换文件的函数,而是一个更有效的函数,可以直接在UTF-8中编写,而无需在文件中添加BOM表:

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

为了荣誉,我在这里https://www.excel-downloads.com/threads/question-de-conversion-en-utf-8-pour-une-vba-qui-enregistre-un-txt.20011510/找到了(Staple1600答案)

0 个答案:

没有答案