0

I am getting a "Next Without for Error on the following code:

sub test()
  numRows = 11
  For i = 0 To numRows
    If Cells(i + 1, 2) >= 0 Then
        Range((Cells(A, i + 1)), Cells(B, i + 1)).Select
        Selection.Copy
        Sheets("PasteLocation").Activate
        Range("Ai+1").Select
        Selection.Paste
  Next
End Sub

I assume that my "If" statement doesnt know that it's done and that the "Next" command thinks there should be another nested "for" in the "if" statement but I do not know where.

5
  • 8
    You should close your If with End If. If then Else Excel VBA - "End If" needed? Commented Jan 24, 2018 at 18:51
  • Yep, that was it. Not sure how I missed that. Commented Jan 24, 2018 at 18:53
  • What does this do? Range("Ai+1").Select Commented Jan 24, 2018 at 18:58
  • "I assume that my 'If' statement doesn't know that it's done" - precisely: you begin an If block but never terminate it - hence the compiler "thinks" Next is part of the If block, can't find a corresponding For statement, and blows up saying exactly that: there's a Next statement that shouldn't be there. All block syntax work the same way, and they can't be intertwined (i.e. you can't start a For loop, begin an If block, then close the For loop with a Next, and then somewhere further down close the If block with End If) Commented Jan 24, 2018 at 19:45
  • There should be questions that result interesting and useful for this community and this could be avoided by checking the code 2 more seconds Commented Jan 24, 2018 at 20:23

2 Answers 2

3

As commented, you need End IF, but I also made some slight improvements:

Sub test()
numRows = 11
For i = 0 To numRows
    If Cells(i + 1, 2) >= 0 Then
        With Sheets("Sheet1")
            .Range(.Cells(1, i + 1), .Cells(2, i + 1)).Copy
        End With
        Sheets("PasteLocation").Range("A" & i + 1).Paste
    End If
Next
End Sub

Note: Change Sheets("Sheet1") to the appropriate sheet name.

Sign up to request clarification or add additional context in comments.

Comments

0

The answer is in the first comment under my original question by user Johnny Mopp

You should close your If with End If. If then Else Excel VBA - "End If" needed?

Comments

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.