我正在尝试创建一个类来保存可变数量的项目(它们本身就是另一个类对象)。
所以,我有第 2 课:
' Class 2 contain each individual quote elements (OTC and MRC) Private pOTC As String Private pMRC As String Public Property Get OTC() As String OTC = pOTC End Property Public Property Let OTC(Value As String) pOTC = Value End Property Public Property Get MRC() As String MRC = pMRC End Property Public Property Let MRC(Value As String) pMRC = Value End Property
然后类 1 包含类 2 的数组:
Private pCurr As String Private pQuote(20) As Class2 Public Property Get Curr() As String Curr = pCurr End Property Public Property Let Curr(Value As String) pCurr = Value End Property Public Property Set Quote(Index As Integer, cQuote As Class2) Set pQuote(Index) = cQuote End Property Public Property Get Quote(Index As Integer) As Class2 Quote = pQuote(Index) End Property
我想做的是:
Dim myQuotes As Class1 Set myQuotes = New Class1 myQuotes.Curr = "GBP" myQuotes.Quote(3).OTC = "1200"
第一行设置 myQuotes.Curr 没有问题,但是当我尝试在数组内设置值时,下一行出现错误,运行时 91 对象变量或未设置 block 变量
有任何关于我做错了什么以及如何设置类数组中元素的值的指示吗?
提前致谢!
最佳答案
当您myQuotes.Quote(3)
时,您调用Property Get Quote
时出现问题。
您的 Class2
内部数组未实例化,因此 pQuote(Index)
引用 Nothing
的数组元素,当您myQuotes.Quote(3).OTC =
您尝试分配给 Nothing
但失败了。
您需要确保pQuote(Index)
已实例化;您可以根据需要执行此操作:
Public Property Get Quote(Index As Integer) As Class2
If (pQuote(Index) Is Nothing) Then Set pQuote(Index) = New Class2
Set Quote = pQuote(Index)
End Property
(注意所需的设置
)
或者通过向Class1
添加初始化例程:
Private Sub Class_Initialize()
Dim Index As Long
For Index = 0 To UBound(pQuote)
Set pQuote(Index) = New Class2
Next
End Sub
关于excel - VBA Class() 对象作为另一个类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17486215/