我使用excel vba读取二进制文件,然后将字节转换为字节数组。但是,在第13行中获取下标超出范围的例外
Sub GetBinaryData()
Dim aryBytes() As Byte
Dim bytInput As Byte
Dim intFileNumber
Dim intFilePos
intFileNumber = FreeFile
Open "Binary.bin" For Binary As #intFileNumber
intFilePos = 1
While Not EOF(intFileNumber)
Get #intFileNumber, intFilePos, bytInput
aryBytes(intFilePos) = bytInput
ReDim aryBytes(UBound(aryBytes) + 1)
intFilePos = intFilePos + 1
Wend
Close #intFileNumber
End Sub
答案 0 :(得分:1)
它失败,因为第一次通过循环aryBytes(intFilePos)
尝试访问不存在的aryBytes
元素1(其声明的动态&前面没有ReDim
)< / p>
此外,EOF不会像您期望的那样进行二进制访问,请尝试使用LOF
这是一种逐字节的方法;
Open "Binary.bin" For Binary Access Read As #intFileNumber
'//only need to dimension once
ReDim aryBytes(LOF(intFileNumber) - 1)
'//easier to count from zero
intFilePos = 0
While intFilePos < LOF(intFileNumber) '//limit to Length-Of-File
Get #intFileNumber, intFilePos + 1, bytInput
aryBytes(intFilePos) = bytInput
intFilePos = intFilePos + 1
Wend
Close #intFileNumber
你也可以一次阅读;
Open "Binary.bin" For Binary Access Read As #intFileNumber
ReDim aryBytes(LOF(intFileNumber) - 1)
Get #intFileNumber, , aryBytes
Close #intFileNumber