2

I have code in hexadecimal format in an excel workbook. Each 2-digit piece of code is in a separate cell, so it looks like 4D|54|68|64|00|00|00|06 etc. There may also be a few cells with 4 or 6 digit pieces, if it makes it any simpler. Is there any way to code a file from here? Effectively I need it so that opening the file in a hex editor will reveal the code. I have a feeling this may involve HEX2DEC or HEX2BIN, but even then I wouldn't know where to go from there.

2
  • What file format is your excel workbook in? Which hex editor are your using? What have you tried so far? Commented Apr 30, 2015 at 18:38
  • .xlsx is default but it has no problem being .xls or .xlsm. Using HxD to check the hex code. I've tried converting hex to ASCII and ANSI and writing that to a .txt, but the conversion back doesn't leave me with the original hex values. Commented Apr 30, 2015 at 18:46

2 Answers 2

3

Might not be the most efficient solution in terms of converting the strings to bytes, but just opening a file in binary mode and putting bytes to it works just fine:

Sub HexStringToBinaryFile()

    Dim hex_val As String
    hex_val = "4D|54|68|64|00|00|00|06"

    Dim output() As String
    output = Split(hex_val, "|")

    Dim handle As Long
    handle = FreeFile
    Open "C:\Dev\test.bin" For Binary As #handle

    Dim i As Long
    For i = LBound(output) To UBound(output)
        Put #handle, , CByte("&H" & output(i))
    Next i

    Close #handle

End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

IT WORKED IT WORKED! This is exactly what I was looking for. Possibly stupid follow up question: is there any way to saveas the .bin file with another file name?
@JamesKissmer - Sure. You can name the output file whatever you want.
1

You didn't actually say what you did but textfile functions do character conversions. Use a stream object in binary mode to write to disk. Use write method to put a byte array into it. And like textfile functions avoid VBA's character or string functions.

Sub test()
     Dim ByteArray(4) As Byte

     ByteArray(0) = CByte(55)
     ByteArray(1) = CByte(55)
     ByteArray(2) = CByte(55)
     ByteArray(3) = CByte(55)

     Set BS = CreateObject("ADODB.Stream")
     BS.Type = 1
     BS.Open
     BS.Write ByteArray
     BS.SaveToFile "c:\users\test", 2

End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.