• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Repeated 'Next Without For' Error - Can't Seem to Fix it

PipBoy808

Member
Code:
For i = 1 To 14

Today = Worksheets("Impending Orders").Range("B3").Value
ConvertDate = Right(Today, 2) & Mid(Today, 4, 2) & Left(Today, 2)
FilePath = Worksheets("Impending Orders").Range("B1").Value
backdate = (Right(ConvertDate, 2) - i)
If Len(backdate) = 1 Then
backdate = "0" & backdate
Else
End If
filedate = Right(Today, 2) & Mid(Today, 4, 2) & backdate
sheetdate = Mid(filedate, 3, 2) & "/" & Mid(filedate, 5, 2) & "/20" & Left(filedate, 2)

FullFileName = GetFullFileName(FilePath, filedate)
Set OrderSource = Workbooks.Open(FilePath & FullFileName)

If OrderSource <> "" Then
OpenMostRecentOrders = True
Exit Function
Else
Next i 'the problem is this next
End If

You can ignore the substance of the code as this is just a syntax problem (Compile error).

I can't get my head around where my syntax is wrong here. It clearly says 'For' at the top, yet Excel keeps returning 'Next Without For'. Can anyone see what I evidently can't?
 
Hi ,

The Next for the For loop is nested within the If ... Else ... Endif.

Move it just below the Endif.

Note that each of the following is a complete construct by itself :

For ... Next
If ... Then ... Else ... Endif
Select Case ... End Select
Do ... Loop Until

and there are many more.

The meaning of complete construct is that the ending keyword ( Next , Endif , End Select , Loop Until ) completes what was begun by the starting keyword ( For , If , Select Case , Do ).

When the program is checked for errors , the first thing that is checked for is whether every starting keyword also has an ending keyword. But this alone is not sufficient.

Nesting means putting one complete construct within another ; thus you can have an If ... Endif statement within a For ... Next statement , or vice-versa ; so also with the other statements. But for this nesting to be correct , one complete construct has to be within another complete construct.

Thus the For ... Next construct has to be entirely within the If ... Endif construct ; the following example does not follow this rule , and will be flagged as an error :
Code:
If ... Then
.
.
  For ...
      .
      .
     
Else
  Next
  .
  .
Endif

For the above code to be correct syntactically , the Next has to be moved above the Else.

Similarly , the following code will also generate an error :
Code:
For ...
    If ... Then
      .
      .
    Else
    .
    .
Next
    .
    Endif

Narayan
 
Last edited:
Back
Top