EXCEL VBAメモ - バイナリファイルアクセス
LOFでファイルサイズを取得できる。Get,Put共、第2引数で位置を指定、第3引数のサイズ分だけ読み書きを行う。
読み取り時bufの不足分は0で埋められる。
Sub accessBinFile() Dim fNo As Long Dim fName As String Dim buf(0 To 4) As Byte Dim pos As Long, i As Long Dim s As String fNo = FreeFile fName = ThisWorkbook.Path & "\sample.txt" ' Textで元データ書き込み Open fName For Output As #fNo Print #fNo, "0123" Print #fNo, "ABCD" Close #fNo ' Binaryで読み込み pos = 1 Open fName For Binary As #fNo Do Until pos > LOF(fNo) ' #は不要 Get #fNo, pos, buf s = "" For i = 0 To UBound(buf) s = s & Right("0" & Hex(buf(i)), 2) & " " Next MsgBox s pos = pos + UBound(buf) + 1 Loop Close #fNo ' 2Byte目を"9"に書き換え Open fName For Binary As #fNo Put #fNo, 2, CByte(Asc("9")) Close #fNo End Sub