VBA Writing file in binary mode (overwriting given byte makes unexpected change in the next one, setting it's value to 0)

Qbik picture Qbik · May 11, 2014 · Viewed 10.9k times · Source

I want to modify part of .bmp file using VBA, everything works great except that, when I overwrite choosen byte, the next byte is being set to zero. My macro is :

Sub WriteBinaryFile()
Dim i As Integer
Dim nFileNum As Integer
Dim sFilename As String

sFilename = "C:\Users\Piotr\Desktop\test1.bmp"

' Get an available file number from the system
nFileNum = FreeFile

' Open the file in binary mode.  Locks are optional

Open sFilename For Binary Lock Read Write As #nFileNum

     ' Put the data in the file
     ' Below code should write 255 value to byte number 100
     ' but it writes also 0 value to byte number 101
     Put #nFileNum, 100, 255 

Close #nFileNum

End Sub

Why when I'm modify byte number 100, value of byte number 101 is setted to 00 ? How to chage it and why is it occour ?

Edit as Cor_Blimey pointed out using conversion function CByte(255) solves problem, because 255 in VBA is integer number, which is 16-bit number so putting it into file overwrites two bytes

Answer

DiegoAndresJAY picture DiegoAndresJAY · Aug 5, 2015

As stated by Cor_Blimey above:

...255 is an integer, which is 16-bit i.e. 2-bytes in VBA. Try Put #nFileNum, 100, CByte(255)