Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA : save a file with UTF-8 without BOM

it's probably sthg simple, here is what I tried :

 Set objStream = CreateObject("ADODB.Stream")
 Set objStreamNoBOM = CreateObject("ADODB.Stream")

 With objStream
        .Open
        .Charset = "UTF-8"
        .WriteText "aaaaaa"
        .Position = 0
    End With

    With objStreamNoBOM
      '.Charset = "Windows-1252"   ' WORK
       .Charset = "UTF-8"          ' DOESN'T WORK!!
       .Open
       .Type = 2
       .WriteText objStream.ReadText
       .SaveToFile "toto.php", 2
       .Close
    End With
    objStream.Close

if the charset is UTF-8, then there is ï» at the beginning of the file.

Any idea on how to save a file with UTF-8 and without BOM?

like image 882
Julien Avatar asked Jul 15 '15 16:07

Julien


1 Answers

In the best of all possible worlds the Related list would contain a reference to this question which I found as the first hit for "vbscript adodb.stream bom vbscript site:stackoverflow.com".

Based on the second strategy from boost's answer:

Option Explicit

Const adSaveCreateNotExist = 1
Const adSaveCreateOverWrite = 2
Const adTypeBinary = 1
Const adTypeText   = 2

Dim objStreamUTF8      : Set objStreamUTF8      = CreateObject("ADODB.Stream")
Dim objStreamUTF8NoBOM : Set objStreamUTF8NoBOM = CreateObject("ADODB.Stream")

With objStreamUTF8
  .Charset = "UTF-8"
  .Open
  .WriteText "aÄö"
  .Position = 0
  .SaveToFile "toto.php", adSaveCreateOverWrite
  .Type     = adTypeText
  .Position = 3
End With

With objStreamUTF8NoBOM
  .Type    = adTypeBinary
  .Open
  objStreamUTF8.CopyTo objStreamUTF8NoBOM
  .SaveToFile "toto-nobom.php", adSaveCreateOverWrite
End With

objStreamUTF8.Close
objStreamUTF8NoBOM.Close

Evidence:

chcp
Active code page: 65001

dir
 ...
15.07.2015  18:48                 5 toto-nobom.php
15.07.2015  18:48                 8 toto.php

type toto-nobom.php
aÄö
like image 108
Ekkehard.Horner Avatar answered Sep 26 '22 15:09

Ekkehard.Horner