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

50,530

Solution 1

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

Solution 2

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:

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.

Share:
50,530
Ubalo
Author by

Ubalo

Updated on July 05, 2022

Comments

  • Ubalo
    Ubalo almost 2 years

    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.

    How can I do that?

  • user202729
    user202729 over 2 years
    To expand: Use StrConv(<string>, vbFromUnicode, <optional locale>) and assign the result to a byte array. Then each byte in the result corresponds to a character in the original string (they must be representable in the current locale). See also vb6 - What does vbFromUnicode mean? - Stack Overflow
  • user202729
    user202729 over 2 years
    To be precise, this makes the byte array equal to the UTF-16-LE encoding of the string content. Which means that each UTF-16 code unit corresponds to 2 bytes, however a character not in the BMP takes up 2 code units and thus 4 bytes.
  • Mark E.
    Mark E. almost 2 years
    The link is dead, but from internet archive the code just had dim b() as byte, then b = StrConv(myString,vbFromUnicode)