如何在 VBA 中将简单字符串转换为字节数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/998746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:50:57  来源:igfitidea点击:

How to convert a simple string to Byte Array in VBA?

excel-vbastringbytearrayvbaexcel

提问by Ubalo

I need to convert a simple string in a Byte array using excel VBA. Then this byte array is used as the request's body.

我需要使用 excel VBA 在 Byte 数组中转换一个简单的字符串。然后这个字节数组被用作请求的主体。

How can I do that?

我怎样才能做到这一点?

Thanks.

谢谢。

采纳答案by Matthew Jones

If you only need ANSI characters, you can use the StrConv() function as is done here.

如果您只需要 ANSI 字符,您可以使用 StrConv() 函数,就像这里所做的那样

回答by Karl E. Peterson

Matthew answered how to convert to ANSI, but if you wanted the resulting byte array to still represent the original Unicode string, you'd simply assign it directly:

Matthew 回答了如何转换为 ANSI,但如果您希望生成的字节数组仍然表示原始 Unicode 字符串,您只需直接分配它:

Public Sub Main()
   Dim b() As Byte
   Dim s As String
   s = "Whatever"
   b = s  'Assign Unicode string to bytes.'
   s = b  'Works in reverse, too!'
   Debug.Print s
End Sub

That's all there is to it. You end up with a 16-element Byte array, each successive pair describing one Unicode character.

这里的所有都是它的。您最终会得到一个 16 元素的 Byte 数组,每个连续的对描述一个 Unicode 字符。

回答by Harry S

' a bit of an example
' had some strings down column  G
' nothing in columns "F" or "H"  so that current works
'  Think about it.. there are many many columns
' so leave blank columns on each side of setsof dats
' then currentregion works ... IFF no blank rows in the data
'
' problem to solve  some text  was  Fred3  John2 Blue3
' others were  Bert 3  Green 2 ... which was the require format
'  the ASC char 1 ..255 are the odd or even
'  numbered bytes if array is 1 based or 0 based
'
Private Sub CommandButton1_Click()
    Dim RV$, Ra As Range, Ri&, AL%, WSA() As Byte
    Dim Ci%, WS$, LV As Byte

    Set Ra = Range("g8").CurrentRegion
    For Ri = 1 To Ra.Rows.Count
        WSA = CStr(Ra(Ri, 1).value)
        AL = UBound(WSA)
        LV = WSA(AL - 1)  ' last char byte value
        If LV > 47 And LV < 58 Then    ' 0 to 9
            If WSA(AL - 3) <> 32 Then    ' no space " "
                ReDim Preserve WSA(AL + 2)    ' allow 1 more char
                WSA(AL - 3) = 32    ' put in space
                WSA(AL - 1) = LV    ' return char
                WS = WSA    ' back to a string
                Ra(Ri, 1) = WS  ' back to the cell
            End If
        End If
    Next Ri
End Sub

' of course  the normal VBAcommands  Instr len Mid replace  &
' would do the job ... but my brain is lazy and needed some exercise