Home » excel » excel – Loop inside loop using multiple variables

excel – Loop inside loop using multiple variables

Posted by: admin May 14, 2020 Leave a comment

Questions:

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
How to&Answers:

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