VBA 以二进制模式写入文件(覆盖给定字节会在下一个字节中发生意外更改,将其值设置为 0)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23590507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:05:39  来源:igfitidea点击:

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

vbafile-iobinaryfileslow-level-io

提问by Qbik

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

我想.bmp使用 VBA修改文件的一部分,一切都很好,除了当我覆盖所选字节时,下一个字节被设置为零。我的宏是:

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 ?

为什么当我修改字节号 100 时,字节号 101 的值设置为 00 ?如何改变它,为什么会发生?

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

编辑Cor_Blimey 指出使用转换函数 CByte(255) 解决了问题,因为255在 VBA 中是整数,它是 16 位数字,因此将其放入文件会覆盖两个字节

回答by DiegoAndresJAY

As stated by Cor_Blimey above:

正如上面 Cor_Blimey 所说:

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

...255 是一个整数,它是 16 位,即 VBA 中的 2 个字节。尝试Put #nFileNum, 100, CByte(255)