帮一个人解决vba的问题,被vba坑了一把,vba写入utf8的时候也写入了bom头,非常讨厌,以前写C#经验是直接文件操作写入方式为binary,可是在vba下,貌似utf8跟type=2似乎没有效果,这一点也就是老外提到的第一点如下:
1. Put the text into the buffer as UTF-8, Type=2, but then set Type=1 (as binary) and write that out. That might convince ADODB.Stream to skip adding the BOM. 2. Create another buffer, as type binary, and use the CopyTo to copy the data to that buffer from a point after the BOM. 3. Read the file in again using Scripting.FileSystemObject, trim off the BOM, write out again
还有2跟3,2说的是从另外一个拷贝buffer拷贝过去,然后再二进制方式写入。第3种没试过觉得应该没问题。现在使用2的方式操作,代码如下:
Set sqlStream = CreateObject("ADODB.Stream") '初始化操作 textStream.Open textStream.Position = 0 textStream.Charset = "UTF-8" '这里写一些数据,调用textSteam.WriteText "xxxxx" Dim binaryStream As Object Set binaryStream = CreateObject("ADODB.Stream") binaryStream.Type = 1 binaryStream.Mode = 3 binaryStream.Open textStream.Position = 3 '跳过BOM3个字节 textStream.CopyTo binaryStream '拷贝过去到二进制stream textStream.Flush textStream.Close binaryStream.SaveToFile textFilename, 2 binaryStream.Close
常用的函数操作方式:
set stream = Server.CreateObject("ADODB.Stream") stream.mode = 3 '1-读,2-写,3-读写 stream.type = 1 '1-二进制,2-文本 stream.Open dataStream.position = index dataStream.CopyTo stream, count '将另一 Stream 对象 dataStream 从 index 到 index+count 的数据拷贝到 stream stream.SaveToFile filePath, 2 '将 stream 数据保存为文件,第二个参数:1-不允许覆盖,2-覆盖写入 stream.Close set stream = nothing