2011-09-02 90 views
2

我有一個類,其中一個成員變量是一個數組。我想分配一個數組到對象,但不斷收到'不能分配數組'編譯錯誤。另外我很好奇如何獲得對象中的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 

回答

0

將數組參數傳遞給類屬性似乎存在問題。

您可以通過設參數切換到一個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 
+0

嘗試了您的解決方案,並且仍然收到相同的錯誤。我應該提到,在我使用ary獲取和讓出屬性之前,我得到了'同一個屬性的屬性過程的定義不一致'錯誤。作爲一種解決方法,將獲取更改爲avry。公共屬性Get ary(ByVal index As Long)As String Public Property讓ary(ByRef Value()As Variant)給出該錯誤。也許這與陣列分配問題有關係。 – postelrich

+0

如果Let/Set和Get類型不同(在您的情況下爲數組或字符串),您應該使用不同的屬性名稱。這就是你最初的「不一致的定義」錯誤告訴你的。請注意,在test()中調用Msgbox()會有問題:屬性ary Get返回一個字符串,但您試圖通過在返回值上調用UBound()將其作爲數組處理。 –

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 

正如蒂姆說,你可以傳遞數組作爲一個變體。你的MsgBox試圖找到一個String數據類型的UBound,所以這是一個問題。另外,你沒有將一個參數傳遞給MsgBox中的ary。 ary屬性返回一個String,但是您使用Set關鍵字,這是另一個問題。

+0

感謝這工作。我沒有使用UBound,而是在數組賦值操作符的for循環中添加了第三個用作計數器的成員變量。另外我不得不宣佈pary爲pary() – postelrich