我正在尝试创建一个类来保存可变数量的项(它们本身就是另一个类对象).
所以,我有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对象变量或With块变量未设置
关于我做错了什么的指针以及如何设置类数组中元素的值?
提前致谢!
当你myQuotes.Quote(3)打电话Property Get Quote哪个有问题.
您的内部数组Class2未实例化,因此当您尝试分配哪个失败时,pQuote(Index)引用数组元素.NothingmyQuotes.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
Run Code Online (Sandbox Code Playgroud)
(注意要求Set)
或者通过添加一个初始化例程来Class1:
Private Sub Class_Initialize()
Dim Index As Long
For Index = 0 To UBound(pQuote)
Set pQuote(Index) = New Class2
Next
End Sub
Run Code Online (Sandbox Code Playgroud)