好吧,我似乎已经自己解决了这个问题,在这里发布答案以防它帮助其他人! :)
将类属性设置为数组(并读取它们)时的注意事项
1) 小心使用括号():不要在 Let 语句中使用它们
Public Property Let ArrayProperty (newArray as variant)
相对于诱惑
Public Property Let ArrayProperty (newArray() as variant)
同样,在使用此属性时不要使用它们,例如:
Class1.ArrayProperty = myArray
myArray 后面没有括号
2) 检查属性 (myArray) Let 语句中的数组是否非空
在此处链接VBA: Don't go into loop when array is empty 到帮助我完成此任务的答案,看来您必须构建自己的函数或使用错误处理来做到这一点,
IsEmpty(myArray)
不会工作。
以及适用于我的目的的代码 sn-p(原始 sn-p 归功于 CreamyEgg):
Public Function IsEmptyArray(TestArray) As Boolean
Dim lngUboundTest As Long
lngUboundTest = -1
On Error Resume Next
lngUboundTest = UBound(TestArray)
On Error GoTo 0
If lngUboundTest >= 0 Then
IsEmptyArray = False
Else
IsEmptyArray = True
End If
End Function
3) 请记住,您可能需要将属性数组重新调整为 Ubound(newArray),例如
Public Property Let Contents (newArray as variant)
'redim pArray to size of proposed array
ReDim pArray(1 To UBound(newArray))
'above line will throw an exception if newArray is empty
pArray = newArray
end Property
4) 故意将类属性设为空数组,我使用了一个临时数组变量,在标准模块开头的子外部公开声明
Public TempArray() As Variant
'outside of Sub ^^
Sub SetClass1ArrayToEmpty
Erase TempArray
class1.ArrayProperty = TempArray
End Sub
erase 方法会使数组为空,我使用它是因为我偶尔使用 TempArray 来制作大小为 1 的数组并想确保它是空的
5) 好消息,将范围设置为类属性似乎与将范围设置为数组的工作方式相同,我使用 application.transpose(myRange) 来避免一列出现问题变成二维数组
class1.ArrayProperty = Application.Transpose(Range(myRange))
你有它,这是工作的类(没有编译错误)
Public Property Get Contents() As Variant
Contents() = pContents()
End Property
Public Property Let Contents(Values As Variant)
'checks for an empty array being passed to it first
If IsEmptyArray(Values) Then
Erase pContents
Else
'redim pContents to size of proposed array
ReDim pContents(1 To UBound(Values))
pContents = Values
End If
End Property
Public Property Get Content(Index As Integer) As String
Content = pContents(Index)
End Property
Public Property Let Content(Index As Integer, Value As String)
Select Case Index
Case Is < 0
'Error Handling
Case Is > UBound(pContents) + 1
'Error Handling
Case Is = UBound(pContents) + 1 'append to end of array
ReDim Preserve pContents(UBound(pContents) + 1)
pContents(Index) = Value
Case Else 'replace some middle part of array
pContents(Index) = Value
End Select
End Property
希望这可以帮助一些窥视者!