Johnny
Johnny

Reputation: 25

Loop inside loop using multiple variables

I am having trouble making a program work in Excel.

I need loop through all the lines in my excel spreadsheet, and loop through multiple possible cells for each line.

Sub DoubleLoop() 
    Dim i As Long
    Dim Carr As Integer

    For i = 2 To 49235
        For j = 2 To 27
            If Range("P" & i).Value = ("Y" & j) And Range("S" & i).Value = ("Z" & j) And Range("P" & i).Value = ("AA" & j) Then
                Range("P" & i).Value = "Keep"
            ElseIf j < 27 Then
                j = j + 1
            ElseIf j = 27 Then
                Range("X" & i).Value = "Remove"
            End If
    Next i
End Sub

Upvotes: 1

Views: 58

Answers (1)

Scott Craner
Scott Craner

Reputation: 152450

As stated in the comments. Use Next j and exit the inner loop when criteria is met.

Sub DoubleLoop()
    Dim i As Long, j As Long
    Dim Carr As Integer

    For i = 2 To 49235
        Range("P" & i).Value = "Remove"
        For j = 2 To 27
            If Range("P" & i).Value = ("Y" & j) And Range("S" & i).Value = ("Z" & j) And Range("P" & i).Value = ("AA" & j) Then
                Range("P" & i).Value = "Keep"
                Exit For
            End If
        Next j
    Next i
End Sub

Upvotes: 2

Related Questions