Help us understand the problem. What is going on with this article?

vba、UTF-8・BOMなしでファイル出力

More than 5 years have passed since last update.

excelのシートのセルにあるデータを元に、utf-8、BOMなしファイルを出力するために実装したもの。

こーど

Public Function writeFile(in_filpth As String, in_buf As String) As Boolean
    writeFile = False
    On Error GoTo Err
    Dim st As New ADODB.Stream
    With st
        .Type = adTypeText
        .Charset = "UTF-8"
        .Open
        .WriteText in_buf
        .Position = 0
        .Type = adTypeBinary
        .Position = 3
        Dim buf As Variant
        buf = .Read()
        .Position = 0
        .Write buf
        .SetEOS
        .SaveToFile in_filpth, adSaveCreateOverWrite
    End With
    st.Close
    Set st = Nothing
    writeFile = True
Err:
    If Err.Number <> 0 Then
        Debug.Print "writeFile(): " & Err.description
    End If
End Function

こーどのせつめい

  • ADODB.Streamを使用
  • 始めにタイプadTypeText、Charset "UTF-8"で、ファイルに出力する内容を書き込む
  • 次に、タイプをadTypeBinaryにして、BOMを飛ばして、書き込んだ内容を変数bufに設定する
  • BOMを潰すために、Positionを0にして、変数bufの内容を書き戻す
  • BOMを潰した分、後ろにゴミが残るので、SetEOSで取り除く
  • SaveToFileでファイルに出力
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away