VBA Class () object as a property of another class

I am trying to create a class to store a variable number of elements (which themselves are an object of the class).

So I have class 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

Then class 1 contains an array of 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

And I would like to do something like:

  Dim myQuotes As Class1
 Set myQuotes = New Class1

 myQuotes.Curr = "GBP"
 myQuotes.Quote (3) .OTC = "1200"  

The first line setting myQuotes.Curr is not a problem, however, when I try to set the value inside the array, the following line errors with the variable Run-time 91 Object or With block variable not set

Any pointers to what I'm doing wrong, and how can I set values ​​for elements in an array of classes?

Thanks in advance!

+6
source share
3 answers

When you myQuotes.Quote(3) call Property Get Quote , which has a problem.

An internal Class2 array is not created, so pQuote(Index) refers to an element of the Nothing array when you then myQuotes.Quote(3).OTC = try to assign Nothing , which fails.

You need to make sure pQuote(Index) installed; You can do this by request:

 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 

(Pay attention to the required Set )

Or by adding the intitialisation routine to Class1 :

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

You need to set them as new class2 in Class1:

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

Just as you do with Class1 in your last script.

+1
source

Maybe it should be

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

Source: https://habr.com/ru/post/948772/


All Articles