Rookie2145
Rookie2145

Reputation: 37

Creating a Loop to Compare two cells in Excel

I have written some code to compare two cells. At the moment the code compares D2 with J2. I need to compare D3 with J3, D4 with J4 etc. I know the easiest way to do it is with a loop but cannot get it working. Any help is much appreciated.

Here is the code so far:

Public Sub Practice1()
    Dim UpLim As Double, LowLim As Double
    Dim outcome As String

    UpLim = Range("d2").Value
    LowLim = Range("j2").Value


    If UpLim > LowLim Then
        result = "Headroom"

    Else
        result = "NoHeadroom"
    End If

    Range("e2").Value = result

End Sub

Upvotes: 0

Views: 1030

Answers (2)

whytheq
whytheq

Reputation: 35605

Slight alternative approach

Public Sub Practice1()

    dim result as string
    dim x as integer
    for x = 2 to 10
      If (cells(x,4) > cells(x,10)) Then
          cells(x,5)= "Headroom"
      Else
          cells(x,5)= "NoHeadroom"
      End If
    next

End Sub

Upvotes: 0

Gary's Student
Gary's Student

Reputation: 96791

Here is a typical loop:

Public Sub Practice1()
    Dim UpLim As Double, LowLim As Double
    Dim outcome As String, i As Long
    For i = 2 To 10
        UpLim = Range("d" & i).Value
        LowLim = Range("j" & i).Value


        If UpLim > LowLim Then
            result = "Headroom"

        Else
            result = "NoHeadroom"
        End If

        Range("e" & i).Value = result
    Next i
End Sub

Pick the i limits to suit your needs.

Upvotes: 2

Related Questions