VBA中的高字节和低字节

时间:2015-10-29 11:29:45

标签: vba excel-vba excel

我尝试从这样的数字中找到低/高字节:

If TextBox1.Value <> "" Then
If TextBox1.Value < 65535 Then
Dim lowByte As Byte
Dim highByte As Byte
Dim number As Long
Dim textBoxValueLong As Long
textBoxValueLong = Val(TextBox1.Value)
lowByte = textBoxValueLong And &HFF&
highByte = Fix(textBoxValueLong / 256)
number = highByte * 256 + lowByte
Worksheets(1).Cells(1, 1) = highByte
Worksheets(1).Cells(1, 2) = lowByte
Worksheets(1).Cells(1, 3) = number
End If
End If

但如果数字低于-255,我在此字符串highByte = Fix(textBoxValueLong / 256)

中出现溢出错误

有什么问题?

UPD:如果我使用这个字符串:highByte = (textBoxValueI And &HFF00&) / 256,可以分成两个字节。但如何合理地合并呢?如果我使用数字<0,我在这里有一个错误:number = highByte * 256 + lowByte

2 个答案:

答案 0 :(得分:1)

将highBite和lowByte声明为Long,然后你就可以合并它们了

但对于低字节,我建议使用mod运算符

lowByte = textBoxValueLong Mod 256

答案 1 :(得分:1)

如果您确实需要loBytehiByte作为Byte并且必须保持在2字节整数范围内,那么以下应该是解决方案:

Sub testInteger()

 Dim sTBV As String

 sTBV = "32767"
 'sTBV = "-32768"

 Dim maxI As Integer
 maxI = 127 * 256 + 255
 Dim minI As Integer
 minI = -128 * 256

 If Val(sTBV) >= minI And Val(sTBV) <= maxI Then

  Dim i As Integer
  i = Val(sTBV)

  Dim loByte As Byte, hiByte As Byte

  loByte = i And &HFF&
  hiByte = (i And &HFF00&) / 256

  Dim j As Integer
  j = Val("&H" & Hex(hiByte) & IIf(Len(Hex(loByte)) = 1, "0" & Hex(loByte), Hex(loByte)))

  MsgBox hiByte & ", " & loByte & ", " & j

 Else

  MsgBox "out of integer range"

 End If

End Sub

2字节整数范围仅为-32768到32767。