0
0

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 1 year has passed since last update.

VBAでファイルをUTF-8/LFに出力しなおす

Posted at

概要

既存のVBAコードでは、Shift_JIS(MS932)で保存する処理が記述されている場合、UTF-8で出力する処理を入れようとするといろいろと面倒な場合、
いったん既存コードを動かしておいて、後でUTF-8に変換する差し込み処理を入れたいというモノグサな方向けのコードです。

既存ファイルを置換したい場合は、第2引数とTrueで呼び出せば、既存ファイルを置換します。
そうでない場合は、拡張子(.utf8.txt)をつけたファイルを出力します。

コード

Option Explicit
​
Sub ConvertFileSJIStoUTF8(fname As String, overwrite As Boolean)
    Dim tmp As String
    Dim buf As String
    Dim tobj As Object
    Dim i As Long
    Dim byteTmp() As Byte
          
    ' ファイルの読み込み
    Dim text As String
    Open fname For Input As #1
        Do Until EOF(1)
            Line Input #1, buf
            text = text & buf & vbLf
        Loop
    Close #1
​
    ' バイナリとして取得+BOM取り除き
    Set tobj = CreateObject("ADODB.Stream")
    tobj.Charset = "UTF-8"
    tobj.Open
    tobj.WriteText text
    tobj.position = 0
    tobj.Type = 1
    tobj.position = 3
    byteTmp = tobj.Read
    tobj.Close
    Set tobj = Nothing 
​
    ' ファイルを出力
    Set tobj = CreateObject("ADODB.Stream")
    tobj.Charset = "UTF-8"
    tobj.LineSeparator = 10
    tobj.Type = 1
    tobj.Open
    tobj.Write byteTmp
    tobj.SetEOS
    tobj.SaveToFile fname & ".utf8.txt", 2
    tobj.Close
    Set tobj = Nothing 

    ' ファイルのリネームを行う
    If overwrite Then
        ' ファイルを削除
        Kill fname
        ' 削除したファイルにリネーム
        Name fname & ".utf8" As fname
    End If
End Sub
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?