excel vba redim limit length of element contents

Gavin Jarvie 1 Reputation point
2021-05-10T15:38:51.687+00:00

I am trying to define an array in vba that is based on a variable number of elements but I want to try and limit the size of the contents of the array elements to a calculated number of characters is this possible?

for example a normal string declaration of size 5 characters in length can be defined as:

Dim MyString As String * 5

is it possible to do something like the below??

ReDim MyArray (1 to MyLastRow) As String * MyCharCount

Reason I want to be able to do this is to loop through a huge number of rows inside an array but want to keep memory requirements lower to enable running code on larger arrays of data inside memory without having to chunk it up. The data being analysed is of type string.

I get a constant expression required error when I compile it so I am guessing no. If any MSFT expert / developer knows a way around this (or anyone else) I'd love to hear from you please.

thanks

Developer technologies | Visual Basic for Applications
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-05-11T19:54:46.727+00:00

    I think that it will work if MyCharCount is a constant:

    Const MyCharCount = 5
    . . .
    ReDim MyArray(1 To MyLastRow) As String * MyCharCount
    

    However, note that definitions like *String*5* allocate five characters, even if the text is shorter. For example:

    Dim s As String * 5
    s = "ab"
    MsgBox "[" & s & "]" ' shows “[ab   ]”
    MsgBox Len(s) ' shows 5
    

    It seems that the system appends spaces. Therefore, in contrast with normal strings, this approach requires additional memory for trailing spaces.

    Theoretically you can declare a class module, that includes the Let and Get properties and which truncates the long strings or raises errors.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.