Search code examples
vbafor-loopnew-operatordivisionbasic

Basic VBA to divide two columns


I'm new to VBA and new to StackOverflow and just trying to follow tutorials to get the hang of things. If I have two columns of numbers, column A and B, I want to divide A/B and put the result into C. I want to use a for loop to do so. The code I have so far is:

Sub ForLooptoDivide()

Dim i As Integer

 For i = 2 To 6

Cells(i, 3).Value = Cells(1, i).Value / Cells(2, i).Value

Next i


End Sub

Like I said, I am brand new to this and have just hit a roadblock with tutorials.

Thanks!


Solution

  • You didn't mention your problem. There many way to do that. Below sub will find last used cell in Column A and then iterate to divide Column A by Column B and put result to Column C. Have a try on it...

    Sub DivideColumns()
    Dim Lastrow As Long
    Dim i As Long
    
        Lastrow = Cells(Rows.Count, "A").End(xlUp).Row
        
        For i = 2 To Lastrow
            Cells(i, "C") = Cells(i, "A") / Cells(i, "B")
        Next i
    
    End Sub
    

    enter image description here