2013-02-06 60 views
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 

回答

1

它無法作爲通過循環aryBytes(intFilePos)嘗試的第一行程訪問的aryBytes不存在元件1(其宣稱動態&沒有前述ReDim

像您期望的二進制訪問,嘗試LOF代替

這裏是一個辦法做到這一點也不會EOF行爲逐字節;

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 
+0

非常感謝Alex – Suresh