VBA Class()对象作为另一个类的属性
我试图创build一个类来容纳可变数量的项目(这本身就是另一个类对象)。
所以,我有第二类:
'2类包含每个单独的报价单元(OTC和MRC) 私人pOTC作为string 私人pMRC作为string 公共属性获取OTC()作为string OTC = POTC 最终财产 公共财产让OTC(价值作为string) pOTC =值 最终财产 公共属性获取MRC()作为string MRC = pMRC 最终财产 公共财产让MRC(价值作为string) pMRC =值 最终财产
然后Class 1包含一个Class 2的数组:
私人pCurr作为string 私人pQuote(20)作为Class2 公共属性获取Curr()作为string Curr = pCurr 最终财产 公共财产让Curr(值作为string) pCurr =值 最终财产 Public Property Set Quote(Index As Integer,cQuote As Class2) 设置pQuote(Index)= cQuote 最终财产 公共属性获取报价(索引整数)作为Class2 Quote = pQuote(Index) 最终财产
而我想要做的是这样的:
Dim myQuotes As Class1 设置myQuotes =新的Class1 myQuotes.Curr =“GBP” myQuotes.Quote(3).OTC =“1200”
第一行设置myQuotes.Curr是没有问题的,但是当我尝试在数组中设置一个值时, 运行时91对象variables或未设置块variables的下一行错误
任何指针,我在做什么错了,我怎样才能设置类数组中的元素的值?
提前致谢!
当你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
添加一个intitialisation例程:
Private Sub Class_Initialize() Dim Index As Long For Index = 0 To UBound(pQuote) Set pQuote(Index) = New Class2 Next End Sub
您需要在Class1中将它们设置为New Class2:
For intI = LBOUND(pQuote) to UBOUND(pQuote) Set pQuote(intI) = New Class2 Next IntI
就像你在最后的脚本中使用Class1一样 。
也许应该是
Public Property Let Quote(Index As Integer, cQuote As Class2) Set pQuote(Index) = cQuote End Property