1

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
6
  • 3
    Whilst editing your question to tidy up your code it became apparent that you appear to be missing Next j from your code. Is that what is causing your error? Commented Oct 17, 2018 at 18:18
  • Next j is missing. Commented Oct 17, 2018 at 18:18
  • 1
    Just a tip, if you correctly format and indent your code in future, simple grammatical errors such as missing Nexts, End Ifs, and other closing statements, become very obvious. Commented Oct 17, 2018 at 18:22
  • 1
    And once you add the Next j, j = j + 1 will be redundant. Commented Oct 17, 2018 at 18:23
  • Thanks for the editing, I'm new to using VBA. If I add in the "Next j" I still get "Remove" on the lines where I should be getting "Keep". Is there something else that is wrong? Commented Oct 17, 2018 at 18:34

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Now that gives me an error at "Next j". Compile error: Next without For

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.