Cannot use class object as argument in other class' method

thingyman Source

I'm new to VBA and was surprised it didn't have an official dynamic array, so I tried to make a simple one that suits my needs:

    Public count As Integer
    Private max As Integer
    Private storage(1 To 5) As DVprogram

    Private Sub class_initialize()
        count = 0
        max = 5
    End Sub

    Public Sub add(data As DVprogram)
        If (count + 1) > max Then
            updateSize (max + 5)
        End If

        storage(count + 1) = data
        count = count + 1
    End Sub

    'more code...

When I try to call add, I get the error "Object doesn't support this property or method."

    Dim test As New DVprogram
    Dim temp As New progDynArray
    temp.add (test)

When I change the array type to Integers, everything works fine, but when I try to use one of my own classes, it always throws this error. I've tried switching between ByVal and ByRef and neither had any affect. I also found this: Passing objects to procedures in VBA, but the solution there doesn't appear to be my problem.

vba

Answers

answered 4 years ago Gopi Bandla #1

Try temp.add test instead of temp.add(test)

answered 4 years ago Tim Williams #2

You need to use Set when assigning objects:

 Set storage(count + 1) = data

and (as noted by Gopi) you need to drop the () when calling your add method:

temp.add test

You don't use parentheses unless you're calling a function or using the Call keyword

EDIT: parentheses (without Call) don't always cause a problem - what they do is cause the argument you're passing to be first evaluated as an expression, and the result of that evaluation then get passed. In the case of updateSize (max + 5) that's not a problem, because that's the behavior you want anyway - to add 5 to max and pass that value to updateSize. In the case of temp.add (test) you don't want test to be evaluated as an expression.

comments powered by Disqus