Forum Discussion

Roshan_K's avatar
Roshan_K
Copper Contributor
Oct 11, 2020
Solved

For Loop to add two columns in Excel

Hi,   I want to use For loops in Excel VBA to add two columns value and update the result in to another column. I have mentioned the table below:   A B C 31 37   95 13   20 14 ...
  • JMB17's avatar
    Oct 11, 2020

    Roshan_K 

     

    I would say for loops are for situations where you know how many times, at most, the loop should iterate whereas Do loops are for instances where you want the loop to repeat while or until a particular condition is reached.

     

    Using your example data (assuming it is in A1:B12 and also assuming your worksheet is the active worksheet as I did not fully qualify my ranges by specifying which worksheet, like Worksheets("Sheet1").Range("A1")):

     

    Sub AddCols1()
         Dim i As Long
         
         For i = 1 To 12
              Range("C" & i).Value = Range("A" & i).Value + Range("B" & i).Value
         Next i
         
    End Sub
    
    Sub AddCols2()
         Dim cell As Range
         
         For Each cell In Range("A1:A12").Cells
              cell.Offset(0, 2).Value = cell.Value + cell.Offset(0, 1).Value
         Next cell
         
    End Sub
    
    Sub AddCols3()
         Dim i As Long
         
         i = 1
         
         Do While Range("A" & i).Value <> ""
              Range("C" & i).Value = Range("A" & i).Value + Range("B" & i).Value
              i = i + 1
         Loop
         
    End Sub

     

Resources