VBA中的高字节和低字节



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

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

将highBite和lowByte声明为Long,您就可以将它们合并为

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

lowByte = textBoxValueLong Mod 256

如果您确实需要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。

最新更新