LoginSignup
2
2

More than 5 years have passed since last update.

[VBA]UTF-8(BOM制御)ファイルを出力する

Last updated at Posted at 2017-12-28

はじめに

利用シーンはあまり無いとおもいますが、[VBA]UTF-8ファイルを出力する でUTF-8出力に対応したので、BOMの制御にも対応してみました。
ポイントは、テキストデータをバイナリに変換してBOM(先頭3バイト)を取り除くだけです。

準備

Visual Basic Editor のメニューから、[ツール]→[参照設定]で、リストから参照設定する。
・Microsoft ActiveX Data Objects x.x Library (最新バージョンのみでOK)

実装

Public Sub SaveFile(ByVal filename As String, ByVal text As String, _
                    Optional ByVal enc As String = "UTF-8", Optional ByVal bom As Boolean = True)

    'BOM対応するために、バイナリにに変換
    Dim Stream: Set Stream = New ADODB.Stream
    Stream.Type = adTypeText
    Stream.Charset = enc
    Stream.Open

    Stream.WriteText text

    Stream.Position = 0
    Stream.Type = adTypeBinary

    'BOMなしにする
    If InStr(enc, "UTF") <> 0 And bom = False Then Stream.Position = 3
    Dim buf: buf = Stream.Read
    Stream.Close

    'ファイル出力
    Dim output: Set output = New ADODB.Stream
    output.Type = adTypeBinary
    output.Open

    output.Write buf
    output.SaveToFile filename, adSaveCreateOverWrite
    output.Close

End Sub
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2