title: Using VBA To Add Specific Cells In A Row Depending On The Value Of A Specific Cell
body: <p>I am trying to sum cells within a row based on the period. So for instance in period 4 I would some cells B2,C2,D2,E2,and F2. I need this "if this then sum this" function to run for all rows that have data entered. As I can have over 200,000 rows, using an excel formula doesn't work. The output of the summing would be the corresponding cell in column O. Below is a shortened version of my code (I didn't figure I needed to post all 12 periods). </p>
  
  <p>When I run the code I get 'Range' of object'_Global' failed and it highlights where I specified the range for Chicken. Also if anyone knows a cleaner way to do this, I'd greatly appreciate it.</p>
  
  <pre><code>Sub AddRowsBySelectedPeriodMacro()
      Sheets("Blah").Select
      Dim LastRow As Long, i As Long, Period As Long, Chicken As Long
      LastRow = ActiveSheet.UsedRange.Rows.Count
      Period = Range("P2")
  
      For i = 2 To LastRow
          If Period = "1" Then
              Chicken = Cells(i, 2).Value + Cells(i, 3).Value
  
          ElseIf Period = "2" Then
              Chicken = Cells(i, 2).Value + Cells(i, 3).Value + Cells(i, 4).Value
  
          Else: Period = "12"
              Chicken = Cells(i, 2).Value + Cells(i, 3).Value + Cells(i, 4).Value + Cells(i, 5).Value + Cells(i, 6).Value + Cells(i, 7).Value + Cells(i, 8).Value + Cells(i, 9).Value + Cells(i, 10).Value + Cells(i, 11).Value + Cells(i, 12).Value + Cells(i, 13).Value + Cells(i, 14).Value
  
          End If
  
          Range("02:O").Value = Chicken
  
      Next i
  
  End Sub
  </code></pre>