2
1

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 3 years have passed since last update.

VBAで様々な文字コードのテキストを読込めるクラスを作った(Win限定?)

Last updated at Posted at 2021-02-11

※ADODB.Stremを使って読み込みます。使えない環境での使用は出来ないと思います

概要

・VBA組み込み関数だとShift_JISしか読み込めない
・たまにUTF-8などの読み込みが必要になったときに調べるのが面倒くさい

ということで、そもそもそんなに困ったことがないけど取り敢えず作ってみたので忘却録として公開します。
以下のコードをコピーして、TextFileReaderという名前でクラスを追加してください。(クラス名は任意でもOK)

TextFileReader.cls

Private adoDBStream As Object ' ADODB.Stream

Property Get CharCode_ASCII() As String: CharCode_ASCII = "ascii": End Property
Property Get CharCode_UTF_7() As String: CharCode_UTF_7 = "UTF-7": End Property
Property Get CharCode_UTF_8() As String: CharCode_UTF_8 = "UTF-8": End Property
Property Get CharCode_Shift_Jis() As String: CharCode_Shift_Jis = "Shift_JIS": End Property
Property Get CharCode_Unicode() As String: CharCode_Unicode = "Unicode": End Property
Property Get CharCode_ISO_2022_JP() As String: CharCode_ISO_2022_JP = "iso-2022-jp": End Property
Property Get CharCode_EUC_JP() As String: CharCode_EUC_JP = "euc-jp": End Property
Property Get CharCode_BigEndianUnicode() As String: CharCode_BigEndianUnicode = "unicodeFFFE": End Property


Private Sub Class_Initialize()

    Set adoDBStream = CreateObject("ADODB.Stream")   'New ADODB.Stream
    
End Sub

Public Function Read(filePath As String, fileFormat As String)

    adoDBStream.Open
    adoDBStream.Type = 2 'adTypeText
    adoDBStream.Charset = fileFormat
    adoDBStream.LoadFromFile filePath
    Read = adoDBStream.ReadText()
    adoDBStream.Close
    
End Function

Private Sub Class_Terminate()

    Set adoDBStream = Nothing
     
End Sub

使用例

TextFileReaderTest.bas
    Dim reader As New TextFileReader
    dim filePath as string : filePath = "C:\hogehoge.txt"
    Dim text as string

    'クラス内の定数?を使って文字コードを指定できます
    text = reader.Read(filePath, reader.CharCode_Shift_Jis) 'Shift_JIS
    text = reader.Read(filePath, reader.CharCode_UTF_8) 'UTF-8
    text = reader.Read(filePath, reader.CharCode_Unicode) 'Unicode
    text = reader.Read(filePath, reader.CharCode_BigEndianUnicode) 'BigEndian Unicode 
    text = reader.Read(filePath, reader.CharCode_ASCII) 'ASCII
    text = reader.Read(filePath, reader.CharCode_EUC_JP) 'EUC_JP
    text = reader.Read(filePath, reader.CharCode_ISO_2022_JP) 'ISO_2022_JP

    set reader = nothing

備考

HKEY_CLASSES_ROOT\MIME\Database\Charset
に登録されている文字コードが使えるようです。

所感など

あまりちゃんと確かめてないので動かなかった場合はごめんなさい。
追加機能としてWriterぐらいはつけても良さそうだけど使わないからなぁ・・・

2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?