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

VBA UTF-8 取り扱いクラス

Last updated at Posted at 2019-08-23

概要

excelでUTF-8の書き出し、読み込みを行う自作クラス

コード

  • クラスモジュール
    clsStream
Option Explicit

'UTF-8読みだし用クラス

Public stream As ADODB.stream
Public buf As String

    
Private Sub Class_Initialize()
    Set stream = New ADODB.stream
    stream.Charset = "UTF-8"
End Sub

' ストリームを開く
Public Sub begin()
    stream.Open
End Sub

Public Sub p(message)
    Debug.Print message
    buf = buf & message & vbCrLf
    stream.WriteText message & vbCrLf
End Sub

Public Sub finish()
    stream.Close
End Sub

Public Sub save(path As String)
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    
    If fso.FileExists(path) Then
        fso.DeleteFile path
    End If
    
    stream.Position = 0 'ストリームの位置を0にする
    stream.Type = adTypeBinary 'データの種類をバイナリデータに変更
    stream.Position = 3 'ストリームの位置を3にする
 
    Dim byteData() As Byte '一時格納用
    byteData = stream.read 'ストリームの内容を一時格納用変数に保存
    stream.Close '一旦ストリームを閉じる(リセット)
 
    stream.Open 'ストリームを開く
    stream.Write byteData 'ストリームに一時格納したデータを流し込む
    
    stream.SaveToFile path
End Sub

' 一括でテキストファイル読み込み
Public Function readAll(path As String) As String
    If path = "" Then
        readAll = ""
        Exit Function
    End If

    With stream
        .Open
        .LoadFromFile path
        readAll = .ReadText
        .Close
    End With
End Function

使い方

参照設定

  • VBAのIDE画面(Excelで alt + F11 で開く、VBA開発画面のこと)を開く

  • 上段のメニューの 「(ツール)」-「参照設定」で以下のライブラリファイルにチェックを追加する

    • Microsoft ActiveX Data Object Library <--- なぜか、ここにUTF-8の読み書きの機能が入っている

ファイル読み込み例

Sub readSample
    Dim s as clsStream
    Set s = new clsStream

    Dim path as String
    path = "C:\hoge\fuga.txt"

    Dim buf as String 
     
    s.begin
    buf = s.readAll
    s.finish

End Sub

ファイルの書き込み例

Sub writeSample
    Dim s as clsStream
    Set s = new clsStream


    Dim buf as String 
     
    s.begin
    s.p "書き込みたい文字"

    Dim path as String
    path = "C:\hoge\fuga.txt"
    s.save path

    s.finish

End Sub
0
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
0
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?