mgr326639
mgr326639

Reputation: 912

Wrong number of arguments or invalid property assignment using classes

Could anyone explain why I get this error on line 12? It is clearly an array. Why can I not obtain the value in index position 0 in this way? Do I really need that extra variable (arr)?

Option Explicit

Dim obj
Set obj = new ClsTest

obj.singleval = "test"
MsgBox obj.singleval                     ' test

obj.repeatingval = split ("a,b,c", ",")
MsgBox IsArray(obj.repeatingval)         ' true
MsgBox UBound(obj.repeatingval)          ' 2
MsgBox obj.repeatingval(0)               ' Wrong number of arguments or invalid
                                         ' property assignment: 'repeatingval'
Dim arr : arr = obj.repeatingval
MsgBox IsArray(arr)                      ' true
MsgBox UBound(arr)                       ' 2
MsgBox arr(0)                            ' a

Class ClsTest
    Private m_singleval
    Private m_repeatingval

    Public Property Get singleval()
        singleval = m_singleval
    End Property

    Public Property Let singleval(w)
        m_singleval = w
    End Property

    Public Property Get repeatingval()
        repeatingval = m_repeatingval
    End Property

    Public Property Let repeatingval(w)
        m_repeatingval = w
    End Property
End Class

Upvotes: 2

Views: 6604

Answers (3)

emno
emno

Reputation: 191

Do I really need that extra variable (arr)?

You can do MsgBox obj.repeatingval()(0)

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

If you want indexed access to the (array) property repeatingval you need to change the property definition to include an index. Beware, though, that getter and setter must be defined alike:

Class ClsTest
    ...
    Public Property Get repeatingval(i)
        repeatingval = m_repeatingval(i)
    End Property

    Public Property Let repeatingval(i, w)
        m_repeatingval(i) = w
    End Property
End Class

You can't have a property where the setter takes an array and the getter returns an element of that array. To be able to assign an array and retrieve an element of that array, you need 2 different properties:

Class ClsTest
    ...
    Public Property Get repeatingval(i)
        repeatingval = m_repeatingval(i)
    End Property

    Public Property Let repeatingval(i, w)
        m_repeatingval(i) = w
    End Property

    Public Property Get repeatingarr
        repeatingval = m_repeatingval
    End Property

    Public Property Let repeatingarr(w)
        m_repeatingval = w
    End Property
End Class

Set obj = New ClsTest

obj.repeatingarr = Split("a,b,c", ",")
MsgBox IsArray(obj.repeatingarr)
MsgBox UBound(obj.repeatingarr)
MsgBox obj.repeatingval(0)

Upvotes: 2

user4285084
user4285084

Reputation:

Dim thing
For Each thing in obj.repeatingval
    msgbox thing
Next

This will give you access to it.

Upvotes: 0

Related Questions