2013-07-05 91 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的做。

相關問題