事实证明,这是解决方案如此简单以至于被包括我自己在内的几个人忽视的罕见情况之一。
? "Byte Arrays" 和 Strings 基本上可以互换。
在 VBA 中,字节数组是特殊的,因为与其他数据类型的数组不同,字符串可以直接分配给字节数组。
在 VBA 中,字符串是 UNICODE 字符串,因此当将字符串分配给字节数组时,它会为每个字符存储两个数字。第一个数字是字符的 ASCII 值,下一个数字是 0。
(来源:VBA Trick of the Week: VBA 中的字节数组 - 有用的Gyaan)
几个代码示例可能比我能解释的更好:
Sub Demo1()
Dim myArr() As Byte, myStr As String
myStr = "Hi!"
myArr() = myStr
Debug.Print "myStr length: " & Len(myStr) 'returns "3"
Debug.Print "Arr bounds: " & LBound(myArr) &"to"& UBound(myArr) 'returns "0 to 5"
myStr = myArr
Debug.Print myStr 'returns "Hi!"
End Sub
在上述情况下,字符串的长度为 3,因此数组的大小为 6。值将以下列方式存储:
myArr(0) = 72 ' ASCII : code for 'H'
myArr(1) = 0 ' ASCII 'null' character
myArr(2) = 105 ' ASCII : code for 'i'
myArr(3) = 0 ' ASCII 'null' character
...etc...
如果想删除这些零,可以使用StrConv 函数。在这种情况下,它将只存储 ASCII 值。
myByteArr() = StrConv("StackOverflow", vbFromUnicode)
就像字符串可以直接赋值给字节数组一样,字节数组也可以直接赋值给字符串。在上面的示例中,如果将myArr 分配给一个字符串,那么它将存储已分配给数组的相同值。
当数组是逐个元素填充的 - 或者,在我的例子中,来自快速文件操作(见下文) - 需要使用StrConv 进行额外的转换步骤。
Sub Demo2()
Dim myArr(0 To 5) As Byte, myStr As String
myArr(0) = 104: myArr(1) = 101: myArr(2) = 108
myArr(3) = 108: myArr(4) = 111: myArr(5) = 33
Debug.Print "myArr bounds: " & LBound(myArr) &"to"& UBound(myArr) 'returns "0 to 5"
'since the array was loaded byte-by-byte, we can't "just put back":
myStr = myArr()
Debug.Print myStr 'returns "???" (unprintable characters)
Debug.Print "myStr length: " & Len(myStr) 'returns "3"
'using `StrConv` to allow for 2-byte unicode character storage
myStr = StrConv(myArr(), vbUnicode)
Debug.Print myStr 'returns "hello!"
Debug.Print "myStr length: " & Len(myStr) 'returns "6"
End Sub
字节数组如何让我的一天变得更好......
我有大型文本文件,我一直想用 VBA 解析/分析,但找不到在加载或逐个字符解析方面不会非常缓慢的方法。
例如,今天我设法在 1/10th 秒内加载了一个 1/4 GB 的文件,并对其进行了解析成一个秒字节数组:
Dim bytes() As Byte
Open myFileName For Binary Access Read As #1
ReDim bytes(LOF(1) - 1&)
Get #1, , bytes
Close #1
For x = LBound(arrOut) To UBound(arrOut)
Select Case bytes(x)
(..and if I want the character)
bytes2(y) = bytes(x)
y = y + 1
End Select
Next x
ReDim Preserve bytes2(LBound(bytes2) To y - 1)
txtIn = StrConv(bytes2, vbUnicode)
...我在 不到 5 秒 内完成了我的完整字符串。 (万岁!)
更多信息: