VBA 保存二进制文件

VBA save binary

我有一个简单的代码

FileName = "h:\OutStr.txt"
Dim BA(1) As Byte
BA(0) = 99
BA(1) = 100

Open FileName For Binary Access Write As #1
lWritePos = 1
Put #1, lWritePos, BA
Close #1

保存后,OutStr.txt 包含预期的两个字节:99 和 100。

但如果我使用函数,结果会有所不同:

Sub BytesToBinaryFile(out_file_name_, vData_)

    Open out_file_name_ For Binary Access Write As #1
    lWritePos = 1
    Put #1, lWritePos, vData_
    Close #1

End Sub


FileName = "h:\OutStr.txt"
Dim BA(1) As Byte
BA(0) = 99
BA(1) = 100

Call BytesToBinaryFile(FileName, BA)

在这种情况下,保存的文件包含一个字节序列,例如:

17 32 1 0 2 0 0 0 0 0 0 0 99 100

任何人都可以向我解释结果的差异吗? 非常感谢!

Sub BytesToBinaryFile(out_file_name_, vData_)

两个变量都是Variant类型。

正确声明它们并且它在函数中也按预期工作

Option Explicit 

Public Sub BytesToBinaryFile(ByVal out_file_name_ As String, ByRef vData_() As Byte)
    Open out_file_name_ For Binary Access Write As #1
    
    Const lWritePos As Long = 1
    Put #1, lWritePos, vData_

    Close #1
End Sub

我建议始终激活 Option Explicit:在 VBA 编辑器中转到 工具选项Require Variable Declaration.

并尽可能好地声明所有变量并尽可能避免Variant