title: Excel VBA - creating a collection class within a parent class
body: <p>I've been trying to create a class that is a collection of objects (of another class) and that is within a parent class. I've looked at several questions here but couldn't get it working. So if anyone can post a short code with my parameters, I'd be very grateful.</p>
  
  <p>My parent class is Sample. It should contain a collection SampleFields which should contain objects from the class SampleField. The SampleField objects have only a Name property and it is taken from cells A1 to D1. It should be possible to add and remove items from the SampleFields collection and modify the Name property of the SampleField objects. The SampleFields collection gets its objects upon the initialization of the Sample class.</p>
  
  <p>I need to access it like this - Sample.SampleFields(1).Name</p>
  
  <p>I think it's useless to post my attempt but here it is:</p>
  
  <pre><code>Sub test()
  
  Dim a As New Sample, i As Variant
  
  a.GetFields
  
  For Each i In a.SampleFields
      Debug.Print i.Name
  Next
  
  End Sub
  </code></pre>
  
  <p>Sample class:</p>
  
  <pre><code>Private pFields As New SampleFields
  
  Public Property Get SampleFields() As SampleFields
      Set SampleFields= pFields
  End Property
  
  Public Property Set SampleFields(ByVal value As SampleFields)
      Set pFields = value
  End Property
  
  Private Sub Initialize_Class()
      Set pFields = New SampleFields
  End Sub
  
  
  Public Sub GetFields()
  
  Dim rngHeaders As Range, rngCell As Range
  Set rngHeaders = Range("A1").CurrentRegion.Rows(1)
  
  For Each rngCell In rngHeaders.Cells
      Dim newField As SampleField
      newField.Name = rngCell.Value2
      Me.Fields.AddNewField (newField)   'crashes here with Method or data member not found
  Next
  
  End Sub
  </code></pre>
  
  <p>SampleFields class:</p>
  
  <pre><code>Private pFields As New Collection
  
  Public Sub AddNewField(FieldName As SampleField)
      Me.AddNewField (FieldName)
  End Sub
  </code></pre>
  
  <p>SampleField class:</p>
  
  <pre><code>Private pName As String
  
  Public Property Let Name(value As String)
      pName = value
  End Property
  
  Public Property Get Name() As String
      Name = pName
  End Property
  </code></pre>
  
  <p>Thanks!</p>