有没有一种方法可以访问VBA中组成字符串的各个字节?

有没有一种方法可以访问VBA中组成字符串的各个字节?,vba,encoding,Vba,Encoding,我想知道组成字符串的确切字节。 这在VBA中可能吗 比如: > Debug.Print toHex("@E") 0x40, 0x45 提出这一问题的理由: 我在使用ServerXMLHTTP时遇到了一些编码问题。 (不确定数据在哪一点被错误解释) 出于调试目的,我想看看字符串中的实际字节是什么,以便缩小问题的来源。我看到您在注释中找到了实际问题的答案,但只是为了回答您的具体问题: 您可以使用下面的toHex方法将字符串转换为原始字节。我在Main中包含了一个用法示例,注释应该解释发生了

我想知道组成字符串的确切字节。
这在VBA中可能吗

比如:

> Debug.Print toHex("@E")
0x40, 0x45

提出这一问题的理由:
我在使用ServerXMLHTTP时遇到了一些编码问题。
(不确定数据在哪一点被错误解释)

出于调试目的,我想看看字符串中的实际字节是什么,以便缩小问题的来源。

我看到您在注释中找到了实际问题的答案,但只是为了回答您的具体问题:

您可以使用下面的
toHex
方法将字符串转换为原始字节。我在
Main
中包含了一个用法示例,注释应该解释发生了什么:

Public Sub Main()
    Dim str As String
    str = "This is a String"

    Debug.Print toHex(str)
End Sub

Public Function toHex(str As String) As String
    'dim an dynamic Byte array
    Dim arrBytes() As Byte

    'When you assign the string to the undimensioned Byte array,
    'VBA automatically resizes it and makes a copy of the individual
    'bytes of the String. Each character is two bytes
    '(I believe VBA uses UTF-16).
    arrBytes = str

    'This prints out the bytes in the way you describe in your question.
    Dim strOut As String
    If UBound(arrBytes) > 0 Then
        strOut = "0x" & arrBytes(0)
        For i = 1 To UBound(arrBytes)
            strOut = strOut & ", 0x" & Hex(arrBytes(i))
        Next
    End If
    toHex = strOut
End Function
编辑:

将字符串分配给字节数组将精确复制字节。就本机而言,VBA使用UTF-16。但是,如果您从另一个源拉入数据,它可能是ASCII或UTF-8。VBA仍将尝试将字符串显示为UTF-16,也就是说,它将尝试将每2个字节(16位)显示为单个字符。通过在字节数组中手动构建ASCII字符串并将其分配给字符串,然后尝试显示它,可以看到此行为:

Public Sub Main()
    Dim strMessage As String

    strMessage = "Hello World!"
    Debug.Print strMessage 'displays "Hello World!" in the immediate window
    Debug.Print toHex(strMessage) 'displays:
    '0x72, 0x0, 0x65, 0x0, 0x6C, 0x0, 0x6C, 0x0, 0x6F, 0x0, 0x20, 0x0, 0x57, 0x0, 0x6F, 0x0, 0x72, 0x0, 0x6C, 0x0, 0x64, 0x0, 0x21, 0x0
    'Note the null bytes because each 2 bytes is a UTF-16 pair

    strMessage = StrConv("Hello World!", vbFromUnicode) 'Converts the immediate string to ASCII and stores it in the VBA String variable
    Debug.Print strMessage 'displays "??????" in the immediate window - 6 unprintable characters because it interprets each two ASCII bytes as a single unprintable UTF-16 character
    Debug.Print toHex(strMessage) 'displays:
    '0x72, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21
    'Note that these are the ASCII bytes of the individual letters

End Sub

你能给我们看看
toHex(“@E”)
的代码吗?描述不清楚,你能再试一试吗?你可能会发现这个有用的[Convert string to unicode][1][1]:VBA中的字符串本机是unicode,而不是ASCII。您想查看Unicode的实际字节,还是想将其转换为ASCII并查看每个字符一个字节?@Blackhawk我想查看字符串的内部表示形式。如果是unicode,那么我希望看到字节组成unicode编码的字符串。@AndyBrazil谢谢。这实际上解决了我的实际问题。(我的问题是我使用了responseText而不是responseBody)。在
arrBytes=str
期间,从
str
复制字节而不做任何更改,或者仍可能进行一些调整。(例如,字符串有时可能是UTF-8,当分配给
byte()
时,它会转换为UTF-16)?@industryworker3595112答案是,它直接复制字节而不进行任何转换。见我的编辑上面。