19
24

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、UTF-8・BOMなしでファイル出力

Last updated at Posted at 2014-06-20

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でファイルに出力
19
24
1

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
19
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?