2013-07-05 47 views
6

我试图创建一个类来容纳可变数目的项目(它们本身是另一个类对象)。作为另一个类的属性的VBA类()对象

所以,我有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的第一行没有问题,但是当我尝试在数组中设置一个值时,下一行错误^ h 运行时间91对象变量或带块变量未设置

任何指针,以什么我做错了,我怎么可以设定值类数组中的元素?

在此先感谢!

+0

除了解决您的问题是由于以下亚历克斯K.,我可以问(为什么好奇)你为什么要这样做,而不是使用一系列引号? – 2013-07-05 11:43:08

回答

4

当你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

或者是附加了intitialisation例程Class1

Private Sub Class_Initialize() 
    Dim Index As Long 
    For Index = 0 To UBound(pQuote) 
     Set pQuote(Index) = New Class2 
    Next 
End Sub 
+0

谢谢!这工作!我也在Class1中发现了另一个错误,因为它应该读取** Set Quote = pQuote(Index)**:'Public Property Get Quote(Index As Integer)Class2 Set Quote = pQuote(Index) End Property' – freudian

0

也许这应该是

Public Property Let Quote(Index As Integer, cQuote As Class2) 
    Set pQuote(Index) = cQuote 
End Property 
1

你需要将它们设置为新的Class2 Class1中:

For intI = LBOUND(pQuote) to UBOUND(pQuote) 
    Set pQuote(intI) = New Class2 
Next IntI 

正如你在你的最终脚本Class1的做。

相关问题