title: Why does this VBA code give me an Object Required error?
body: <p>I have the following code in an Excel macro:</p>
  
  <pre><code>Dim cellRange As range
  Dim cell As range
  Dim cellFormula As String
  Dim yearCells As New Collection
  
  For Each cellRange In ranges
      For Each cell In cellRange.Cells
          cellFormula = GetCellFormula(cell)
          If (cellFormula = formulaYears) Then
              yearCells.Add (cell)
          End If
      Next
  Next
  </code></pre>
  
  <p>Where <code>ranges</code> is a <code>Collection</code> object holding many Range objects.</p>
  
  <p>When I run the code, I get an "Object required" error on the line <code>For Each cellRange In ranges</code>. Why is this? After all, <code>cellRange</code> is declared as an object, i.e. <code>Dim cellRange As range</code>. If I convert the code to a <code>For</code> loop, I have the same error on a line:</p>
  
  <pre><code>Set cellRange = ranges(i)
  </code></pre>
  
  <p>BTW, my VBA IDE insists on <code>range</code> always having a lower case initial letter. When I type <code>Range</code> the editor "corrects" it to <code>range</code>. Yet other code using <code>range</code> objects works fine.</p>