【问题标题】:how can I read a binary file using VBA?如何使用 VBA 读取二进制文件?
【发布时间】:2009-03-18 22:11:06
【问题描述】:

我有一个由 Compaq Visual Fortran 编写的程序生成的二进制文件。 如何读取特定行并将它们保存在 Excel 工作表中?

【问题讨论】:

  • 二进制文件怎么有“行”?

标签: vba binary


【解决方案1】:

如果要将整个文件读入一个大数组,可以使用以下代码:

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

结果与 Todd Owen 的答案相同,但没有使用外部库。

【讨论】:

    【解决方案2】:

    您必须使用“二进制访问”打开它。

    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
    

    【讨论】:

      【解决方案3】:

      另一种方法是使用 ADODB.Stream:

      With CreateObject("ADODB.Stream")
          .Open
          .Type = 1  ' adTypeBinary
          .LoadFromFile file.Path
          bytes = .Read
          .Close
      End With
      

      (抱歉,我实际上并不确定它在哪个库中,这就是为什么此示例代码使用 CreateObject 和字面值 1 而不是命名常量 adTypeBinary!)

      【讨论】:

      • 库是 Microsoft Active Data Object。
      • 为什么要使用外部库来完成如此琐碎的内置任务?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2019-04-13
      • 2020-11-11
      • 2012-09-11
      相关资源
      最近更新 更多