如何使用 VBA 读取二进制文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/660312/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can I read a binary file using VBA?
提问by
I have a binary file that resulted from a program written in Compaq Visual Fortran. How can I read specific lines and save them in an Excel sheet?
我有一个由 Compaq Visual Fortran 编写的程序生成的二进制文件。如何读取特定行并将它们保存在 Excel 工作表中?
回答by Curtis Inderwiesche
You have to open it using "Binary Access".
您必须使用“二进制访问”打开它。
See http://www.vbforums.com/showthread.php?t=430424
见http://www.vbforums.com/showthread.php?t=430424
Sub Temp()
    Dim intFileNum%, bytTemp As Byte, intCellRow%
    intFileNum = FreeFile
    intCellRow = 0
    Open "C:\temp.bin" For Binary Access Read As intFileNum
    Do While Not EOF(intFileNum)
        intCellRow = intCellRow + 1
        Get intFileNum, , bytTemp
        Cells(intCellRow, 1) = bytTemp
    Loop
    Close intFileNum
End Sub
回答by Erik A
If you want to read the entire file into one big array, you can use the following code:
如果要将整个文件读入一个大数组,可以使用以下代码:
Dim byteArr() As Byte
Dim fileInt As Integer: fileInt = FreeFile
Open "C:\path\to\my\file.ext" For Binary Access Read As #fileInt
ReDim byteArr(0 To LOF(fileInt) - 1)
Get #fileInt, , byteArr
Close #fileInt
The result is identical to the answer by Todd Owen, but achieved without the use of external libraries.
结果与 Todd Owen 的答案相同,但在不使用外部库的情况下实现。
回答by Todd Owen
Another way is using ADODB.Stream:
另一种方法是使用 ADODB.Stream:
With CreateObject("ADODB.Stream")
    .Open
    .Type = 1  ' adTypeBinary
    .LoadFromFile file.Path
    bytes = .Read
    .Close
End With
(Sorry, I'm not actually sure what library it's in, which is why this sample code uses CreateObject and the literal value 1 instead of the named constant adTypeBinary!)
(抱歉,我实际上不确定它在哪个库中,这就是为什么此示例代码使用 CreateObject 和文字值 1 而不是命名常量 adTypeBinary 的原因!)

