Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile error: Next without For || VBA

Tags:

excel

vba

I have a problem with my code, an error appears, and I don;t understand why. The error is:
"Compile error: Next without For"
I do not understand why it is like that. I am new to coding so any help and comments are more than welcome.
This is the code, the Next which is pointed as the one without For is provided a comment.

Sub CGT_Cost()
startrow = Worksheets("GUTS").Cells(10, 1) 'Here I put 1
endrow = Worksheets("GUTS").Cells(11, 1)   'Here I put 1000

For x = endrow To startrow Step -1

If Cells(x, "Q").Value = "Sale" Then

    If Cells(x, "D").Value = "1" Then

    For i = 1 To 1000

        If Cells(x - i, "R").Value <> "1" Then

    Next i
        Else
        Range("G" & x).FormulaR1C1 = "=R[-" & i & "]C/R[-" & i & "]C[-1]*RC[-1]"

        End If
    End If
    End If
Next x  

End Sub  

Thank you all in advance, with best regards,
Artur.

like image 760
Artur Rutkowski Avatar asked Aug 14 '13 13:08

Artur Rutkowski


2 Answers

Every For statement with a body must have a matching Next, and every If-Then statement with a body must have a matching End If.

Example:

For i = 1 To 10 '<---- This is the header

    Hello(i) = "Blah"  '<---- This is the body

Next i  '<---- This is the closing statement

You have part of the body of your If statement inside your For i loop, and part of it outside. It has to be either ALL inside or ALL outside. Think through the logic and see what it is you want to do.

like image 144
jlaverde Avatar answered Oct 06 '22 05:10

jlaverde


you have overlapping loops-perhaps

Sub CGT_Cost()
   startrow = Worksheets("GUTS").Cells(10, 1)   'Here I put 1
   endrow = Worksheets("GUTS").Cells(11, 1)   'Here I put 1000

   For x = endrow To startrow Step -1

      If Cells(x, "Q").Value = "Sale" Then

         If Cells(x, "D").Value = "1" Then

            For i = 1 To 1000

               If Cells(x - i, "R").Value <> "1" Then
                  '
               Else
                  Range("G" & x).FormulaR1C1 = "=R[-" & i & "]C/R[-" & i & "]C[-1]*RC[-1]"
               End If

            Next i

         End If

      End If

   Next x

End Sub
like image 36
JosieP Avatar answered Oct 06 '22 04:10

JosieP