无法使用数组成员变量分配数组

时间:2011-09-02 16:52:51

标签: arrays excel class vba object

我有一个类,其中一个成员变量是一个数组。我试图为对象分配一个数组,但继续得到'无法分配数组'编译错误。另外,我很好奇如何在对象中获取数组的UBound。 UBound(obj.array)无法编译。我正在使用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

2 个答案:

答案 0 :(得分:1)

这对我有用

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

正如Tim所说,您可以将数组作为变体传递。你的MsgBox试图找到一个字符串数据类型的UBound,所以这是一个问题。另外,你没有在MsgBox中向ary传递参数。 ary属性返回一个String,但您使用的是Set关键字,这是另一个问题。

答案 1 :(得分:0)

将数组参数传递给类属性似乎存在问题。

您可以通过将Let参数切换为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