VBA Byte

示例

Dim Value As Byte

字节是无符号的8位数据类型。它可以表示0到255之间的整数,并且尝试存储该范围之外的值将导致运行时错误6 :Overflow。字节是VBA中唯一可用的固有无符号类型。

转换为Byte的强制转换函数为CByte()。对于浮点类型的转换,结果四舍五入为最接近的整数值,四舍五入为.5。

字节数组和字符串

字符串和字节数组可以通过简单的分配相互替换(无需转换函数)。

例如:

Sub ByteToStringAndBack()

Dim str As String
str = "Hello, World!"

Dim byt() As Byte
byt = str

Debug.Print byt(0)  ' 72

Dim str2 As String
str2 = byt

Debug.Print str2    ' Hello, World!

End Sub

为了能够编码Unicode字符,字符串中的每个字符占用数组中的两个字节,最低有效字节在前。例如:

Sub UnicodeExample()

Dim str As String
str = ChrW(&H2123) & "."  ' Versicle character and a dot

Dim byt() As Byte
byt = str

Debug.Print byt(0), byt(1), byt(2), byt(3)  ' Prints: 35,33,46,0

End Sub