title: Excel VBA: Adding objects to a collection within a class
body: <p>I am trying to create a class (named ClassSection) that contains a collection (named DefectCollection). It needs a function to add items to that collection but I'm having trouble making it work. I get Error 91 "Object variable or with block variable not set."</p>
  
  <p>I have looked at the other answers on here, which is what got me this far, but I don't understand what I'm missing.</p>
  
  <p>Here is the class module code:</p>
  
  <pre><code>Public DefectCollection As Collection
  
  Private Sub Class_Initialise()
      Set DefectCollection = New Collection
  End Sub
  
  Public Function AddDefect(ByRef defect As CDefect)
      DefectCollection.Add defect [&lt;---- error 91]
  End Function
  </code></pre>
  
  <p>And here is the code that calls the function: ('defect' is another class, which works fine - I want each 'ClassSection' to be able to hold an unlimited number of 'defects')</p>
  
  <pre><code>Dim SC As Collection
  Dim section As ClassSection
  Set SC = New Collection
  
  Dim SurveyLength As Double
  
  For Each defect In DC
      SurveyLength = WorksheetFunction.Max(SurveyLength, defect.Pos, defect.EndPos)
  Next defect
  
  SurveyLength = Int(SurveyLength)
  
  For i = 0 To numSurveys
      For j = 0 To SurveyLength
          Set section = New ClassSection
          section.ID = CStr(j &amp; "-" &amp; dates(i))
          SC.Add Item:=section, Key:=section.ID
      Next j
  Next i
  
  
  Dim meterage As Double
  
  For Each defect In DC
      meterage = Int(defect.Pos)
      Set section = SC.Item(meterage &amp; "-" &amp; defect.SurveyDate)
      section.AddDefect defect
  Next defect
  </code></pre>
  
  <p>Thanks!</p>