3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VBAでBOM無しのUTF-8ファイルを作成する

Last updated at Posted at 2019-07-31

はじめに

VBAでUTF-8ファイルを作成する時、通常はこのような方法で作成する。

test.xlsm
Sub test()

    Const FILE_NAME As String = "C:\Users\xxxx\test.txt"
    Const BODY      As String = "あいうえお"

    With CreateObject("ADODB.Stream")
        .Charset = "UTF-8"
        .Open
        .WriteText BODY
        .SaveToFile FILE_NAME, 2
        .Close
    End With

End Sub

出来上がったファイルを見ると、BOM有りで出力されていた。BOM無しファイルを出力するにはもう一工夫必要そうだ。

BOM無しファイルを作成する

test.xlsm
Sub test()

    Const FILE_NAME As String = "C:\Users\xxxx\test.txt"
    Const BODY      As String = "あいうえお"
    
    Dim adodb1 As Object
    Dim adodb2 As Object
    
    Set adodb1 = CreateObject("ADODB.Stream")
    Set adodb2 = CreateObject("ADODB.Stream")

    With adodb1
        .Charset = "UTF-8"
        .Open
        .WriteText BODY
        .Position = 3
        With adodb2
            .Type = 1
            .Open
            adodb1.CopyTo adodb2
            .SaveToFile FILE_NAME, 2
            .Close
        End With
        .Close
    End With

End Sub

これでBOM無しファイルを出力することができた。

3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?