Home » excel » excel – Divide each cell in a range by a cell on the same row

excel – Divide each cell in a range by a cell on the same row

Posted by: admin May 14, 2020 Leave a comment

Questions:

I need to divide a variable range by a cell from a static column, but variable row. My range will always start in cell J2, but could end anywhere. The static column is always H. So my ask is to divide J2 by H2, then K2 by H2, L2 by H2 (end of row); divide J3 by H3, etc.

I am close with the code I have, but I cannot get the row and next cell to progress in tandem. Either the calculation is always placed in J2, or it always uses the value in H2 instead of progressing to H3, H4, etc. when the rest of the row progresses.

In the example of my code below it is the latter of the two issues:

Dim rng As Range, e As Long, lastrow As Long, lastcol As Long

lastcol = Sheets("Group_PositionList").Cells(1, Columns.Count).End(xlToLeft).Column
lastrow = Sheets("Group_PositionList").Cells(Rows.Count, 1).End(xlUp).Row

Set rng = ActiveSheet.Range(Cells(2, 10), Cells(lastrow, lastcol))

For e = 2 To lastrow
    For Each Cell In rng
        If Cell.Value > 0 Then
            Cell.Value = Cell.Value / Cells(e, 8).Value
        End If
    Next
Next e
End Sub

I see that the process isn’t getting to the “Next e” line, but I cannot for the life of me come up with the syntax to get it there. Do I need another level to the loop?

How to&Answers:

Use a for loop to iterate the columns:

Dim rng As Range, e As Long, i As Long, lastrow As Long, lastcol As Long
With Sheets("Group_PositionList")
    lastcol = .Cells(1, Columns.Count).End(xlToLeft).Column
    lastrow = .Cells(Rows.Count, 1).End(xlUp).Row



    For e = 2 To lastrow
        For i = 10 To lastcol
            If .Cells(e, i).Value > 0 Then
                .Cells(e, i).Value = .Cells(e, i).Value / .Cells(e, 8).Value
            End If
        Next
    Next e
End With

But using a variant array will be quicker:

Dim rng, mRng, e As Long, i As Long, lastrow As Long, lastcol As Long
With Sheets("Group_PositionList")
    lastcol = .Cells(1, Columns.Count).End(xlToLeft).Column
    lastrow = .Cells(Rows.Count, 1).End(xlUp).Row


    rng = .Range(Cells(2, 10), Cells(lastrow, lastcol)).Value
    mRng = .Range(Cells(2, 8), Cells(lastrow, 8)).Value

    For e = LBound(rng, 1) To UBound(rng, 1)
        For i = LBound(rng, 2) + 2 To UBound(rng, 2)
            If rng(e, i).Value > 0 Then
                rng(e, i).Value = rng(e, i).Value / mRng(e, 1).Value
            End If
        Next
    Next e

    .Range(Cells(2, 10), Cells(lastrow, lastcol)).Value = rng

End With