※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ぐらいはつけても良さそうだけど使わないからなぁ・・・