Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VBA save binary

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading