LoginSignup
4
6

More than 5 years have passed since last update.

VBAでバイナリファイルを読み込む方法 VBAで簡易バイナリビューア

Posted at

VBAでのテキストファイル入出力の方法はよく知られていますが、バイナリファイルの扱い方はあまり知られていません。
自分が初学者の頃、よくわからなかったので、ここに記したいと思います。
For Binary という宣言と Get 命令を使う部分がポイントです。

例として、バイナリエディタを作れるとよいのですが、サンプルとしては、それは冗長になるので、バイナリビューアを作ってみたいと思います。

Excel上で動作します。

以下のソースとなります。

ソース
Sub Main()

    'ファイル選択ダイアログでファイルを指定
    Dim vFilePath As Variant
    vFilePath = Application.GetOpenFilename

    'キャンセルボタンを押されたら、処理終了
    If vFilePath = False Then
        End
    End If

    'ファイルサイズが0バイトの場合も処理終了
    Dim nFileLen As Long
    nFileLen = FileLen(vFilePath)
    If nFileLen = 0 Then
        End
    End If

    '空いているファイル番号を取得
    Dim iFile As Integer
    iFile = FreeFile

    '指定されたファイルを取得したファイル番号としてバイナリモードで開く
    Open vFilePath For Binary As #iFile

    'ファイルサイズ分のバイト配列を用意
    Dim bData() As Byte
    ReDim bData(0 To nFileLen - 1)

    'バイト配列に指定ファイルを展開
    Get #iFile, , bData
    Close #iFile

    Dim i As Long
    'ScreenUpdatingやらCalculationなどの高速化設定は割愛
    'バイナリデータをダンプ表示します。
    For i = 0 To nFileLen - 1
        y = i \ 16 + 1
        x = i Mod 16 + 1
        Cells(y, x) = "'" & Right("0" & Hex(bData(i)), 2)
    Next

End Sub

これが古くからのVBAでのやり方です。(ただし、弱点があり、ファイルパスに中国語文字などのUnicode文字が入ると、エラーとなります。)

4
6
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
4
6