我正在尝试创建一个类来保存可变数量的项(它们本身就是另一个类对象)。
所以,我有第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
然后Class 1包含Class 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对象变量或者没有设置块变量
关于我做错了什么的指针以及如何设置类数组中元素的值?
提前致谢!
答案 0 :(得分:5)
当您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
(注意所需的Set
)
或者通过向Class1
添加一个初始化例程:
Private Sub Class_Initialize()
Dim Index As Long
For Index = 0 To UBound(pQuote)
Set pQuote(Index) = New Class2
Next
End Sub
答案 1 :(得分:2)
您需要在Class1中将它们设置为New Class2:
For intI = LBOUND(pQuote) to UBOUND(pQuote)
Set pQuote(intI) = New Class2
Next IntI
就像在最终脚本中使用 Class1 一样。
答案 2 :(得分:0)
也许它应该是
Public Property Let Quote(Index As Integer, cQuote As Class2)
Set pQuote(Index) = cQuote
End Property