Home > OS >  VBA save binary
VBA save binary

Time:04-22

I have a simple code

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

After saving, OutStr.txt contains two bytes as expected: 99 and 100.

But the result is different in case I am using a function:

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)

In this case the saved file conatins a sequence of bytes, like:

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

Could anybody explain me the difference in the results? Many thanks in advance!

CodePudding user response:

In

Sub BytesToBinaryFile(out_file_name_, vData_)

both variables are of type Variant.

Declare them properly and it works as expected in the function as well

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

I recommend always to activate Option Explicit: In the VBA editor go to ToolsOptionsRequire Variable Declaration.

And declare all variables as good as possible and avoid Variant whenever you can.

  • Related