0

I can declare a static byte array in VBA like this, but it appears that the elements are not of type byte.

Dim A As Variant
A = Array(&H9F, &H2C, &H3B, &HFF, &H84)

I can solve this by copying the content to a second array, but that doesn't look very efficient to me.

Dim A As Variant
A = Array(&H9F, &H2C, &H3B, &HFF, &H84)
Dim N As Long: N = UBound(A)
Dim B() As Byte
ReDim B(N)
For X = 0 To N
    B(X) = A(X)
Next

So my question is: is there a better or more elegant way to do this?

1 Answer 1

2

ok, probably not the solution you were looking for, but you can convert a string directly to a byte array..

So, for your example, something (crazy) like this will work..

Dim bResult() As Byte
bResult = StrConv(Join(Array(Chr(&H9F), Chr(&H2C), Chr(&H3B), Chr(&HFF), Chr(&H84)), vbNullString), vbFromUnicode)

A second method would be to update the elements in the original array. it still requires a loop, but the entries will then by Bytes

Dim i As Long
Dim vValues As Variant: vValues = Array(&H9F, &H2C, &H3B, &HFF, &H84)
For i = LBound(vValues) To UBound(vValues)
    vValues(i) = CByte(vValues(i))
Next i

Finally you could just do this:

Dim vValues As Variant 
vValues = Array(CByte(&H9F), CByte(&H2C), CByte(&H3B), CByte(&HFF), CByte(&H84))
Sign up to request clarification or add additional context in comments.

2 Comments

I was aware of the fact that you can assign a string directly to a byte array. Only I would have used a for loop to join the elements,, which I wanted to avoid. Your solution is a bit cleaner, but like you said, still not the one I was looking for.
yeah, it's probably the only solution without using a loop sadly. Ive added a second method. updating the type of each array element is slightly better than using a second array it think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.