1

我正在使用 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
4

1 回答 1

1

它在第一次通过循环aryBytes(intFilePos)尝试访问aryBytes不存在的元素 1 时失败(其声明为动态且没有前导ReDim

此外,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
于 2013-02-06T12:05:53.387 回答