0

Is it possible in Excel VBA to read a binary file to a variable?

A function similar to:

function bin2var(filename as String) As XXXX

And also, is it possible to do the reverse operation?

function var2bin(filename as String,data as XXXX)
  • 1
    What makes you think it isn't possible..? What have you tried so far that doesn't work..? – Sean Dec 04 '11 at 18:31
  • It's totally possible. But what kind of variable do you want? A Byte array, or a String? – Boann Dec 04 '11 at 18:34
  • @Sean This:http://stackoverflow.com/questions/660312/how-can-i-read-a-binary-file-using-vba but it's not exactaly what I need... –  Dec 04 '11 at 18:34
  • @Diga: You accepted my answer very fast. Make sure you copied the version with the #1/#f fix. – Boann Dec 04 '11 at 19:00

2 Answers2

3
Function bin2var(filename As String) As String
    Dim f As Integer
    f = FreeFile()
    Open filename For Binary Access Read Lock Write As #f
        bin2var = Space(FileLen(filename))
        Get #f, , bin2var
    Close #f
End Function

Sub var2bin(filename As String, data As String)
    Dim f As Integer
    f = FreeFile()
    Open filename For Output Access Write Lock Write As #f
        Print #f, data;
    Close #f
End Sub
Boann
  • 48,794
  • 16
  • 117
  • 146
2

Rewriting Boann's code as it writes a new line (2 byte) at the end of the output file.

Function bin2var(filename As String) As String
    Dim f As Integer
    f = FreeFile()
    Open filename For Binary Access Read Lock Write As #f
        bin2var = Space(FileLen(filename))
        Get #f, , bin2var
    Close #f End Function

Sub var2bin(filename As String, data As String)
    Dim f As Integer
    f = FreeFile()
    Open filename For Binary Access Write As #f
        Put #f, , data
    Close #f 
End Sub
bpelhos
  • 2,078
  • 1
  • 13
  • 6