0

Working in Excel VBA, and I am trying to initialize an array of several objects of the class "CUserType", but I am having some trouble. I tried doing this in a loop, like this:

For count = 1 To size
    Dim myArray(count)   As CUserType
Next

However, it looks like VBA wants the array index to be a constant integer.

Now I am trying to do it with a separate function, like this:

Sub ititUsers(num As Integer)

Dim myArray()           As CUserType
Redim myArray(1 to num)

If num = 1 Then
    Dim myArray(1)      As CUserType
ElseIf num = 2 Then
    Dim myArray(1)      As New CUserType
    Dim myArray(2)      As New CUserType
ElseIf num = 3 Then
    Dim myArray(1)      As New CUserType
    Dim myArray(2)      As New CUserType
    Dim myArray(3)      As New CUserType
.
.
.
End Sub

But of course this is both tedious and wasteful. I am new to this, so I know I am probably missing something. Any help?

Thank you!

1 Answer 1

2

Your line Dim myArray(count) As CUserType is already setting all elements of the array as CUserType. If you just need to initialize it, then do a For Loop:

Sub ititUsers(num As Integer)

    Dim i As Long
    Dim myArray() As CUserType
    Redim myArray(1 to num)

    For i = 1 to num
        Set myArray(i) = New CUserType
    Next i

End Sub
Sign up to request clarification or add additional context in comments.

Comments

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.