user590715
user590715

Reputation:

VBA - Read 15 MB binary file to var

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)

Upvotes: 0

Views: 7975

Answers (2)

bpelhos
bpelhos

Reputation: 2148

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

Upvotes: 2

Boann
Boann

Reputation: 50041

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

Upvotes: 3

Related Questions