Reputation: 3486
I have a class where one of the member variables is an array. I am trying to assign an array to the object but keep getting the 'Can't assign array' compile error. Also I was curious as how to get UBound of the array in object. UBound(obj.array) doesn't compile. I am using excel 07 vba.
'Test routine that keeps failing
Sub test()
Dim Arr(2) As String
Arr(0) = ""
Arr(1) = "Pizza"
Arr(2) = "Hoes"
Dim obj As Cats
Set obj = New Cats
obj.avry = Arr
obj.field = 4
MsgBox UBound(obj.ary)
End Sub
'Class declaration
Private pary() As String
Private pfield As Long
Public Property Get ary(ByVal index As Long) As String
Set ary = pary(index)
End Property
Public Property Let avry(Value() As String)
ReDim pary(UBound(Value)) As String
For i = LBound(Value) To UBound(Value)
pary(i) = Value(i)
Next i
End Property
Public Property Get field() As Long
field = pfield
End Property
Public Property Let field(Value As Long)
pfield = Value
End Property
Private Sub Class_Initialize()
pfield = 0
End Sub
Upvotes: 2
Views: 1879
Reputation: 33145
This worked for me
Sub test()
Dim Arr(2) As String
Arr(0) = ""
Arr(1) = "Pizza"
Arr(2) = "Hoes"
Dim obj As Cats
Set obj = New Cats
obj.avry = Arr
obj.field = 4
MsgBox obj.ary(2)
End Sub
Public Property Get ary(ByVal index As Long) As String
ary = pary(index)
End Property
Public Property Let avry(vValue As Variant)
ReDim pary(UBound(vValue)) As String
Dim i As Long
For i = LBound(vValue) To UBound(vValue)
pary(i) = vValue(i)
Next i
End Property
Public Property Get field() As Long
field = pfield
End Property
Public Property Let field(Value As Long)
pfield = Value
End Property
Private Sub Class_Initialize()
pfield = 0
End Sub
As Tim said, you can pass the array as a variant. Your MsgBox is trying to find a UBound of a String data type, so that was a problem. Also, you weren't passing an argument to ary in the MsgBox. The ary property returns a String, but you were using the Set keyword, which was another problem.
Upvotes: 1
Reputation: 166126
There seems to be an issue with passing array parameters to class properties.
You can get around this by switching the Let parameter to a Variant:
Public Property Let avry(ByRef arrVal As Variant)
Dim i As Integer
If IsArray(arrVal) Then
ReDim pary(LBound(arrVal) To UBound(arrVal))
For i = LBound(arrVal) To UBound(arrVal)
pary(i) = arrVal(i)
Next i
End If
End Property
Upvotes: 0