VBA tip – please don’t leave your Next blank

Include the variable

In a For Next loop you don’t have to include the variable in the Next statement. But ….

This means the code below is ok.

Sub ForNextExample1()
 
Dim i
 
    For i = 1 To 12
 
        Selection(1).Offset(0, i) = i
 
    Next
 
End Sub

In a single For Next loop this may not be an issue. If you have multiple nested For Next loops it can make it hard to track which Next is matched to which For. Also if you miss a Next then again tracking is more difficult.

Sub ForNextExample2()
 
Dim i, r, c
 
    For i = 1 To 12
        For r = 1 To 10
            For c = 1 To 5
                Selection(1).Offset(r * i, c * i) = i
            Next
        Next
    Next
 
End Sub

So please include the variable in the Next statement.

It takes next to no time and makes your code more readable and trackable.

Sub ForNextExample3()
 
Dim i, r, c
 
    For i = 1 To 12
        For r = 1 To 10
            For c = 1 To 5
                Selection(1).Offset(r * i, c + i) = i
            Next c
        Next r
    Next i
 
End Sub

Added 1 September 2020.

Alfred posted a comment that I thought was worth adding to this post.

“If you ever have to work with someone else’s VBA code that has a great number of blank NEXT lines, consider using NotePad++.
It support a VB language setting which will indent all the FOR/NEXT structures for you.
NotePad++ is freeware and a life saver.
For one of my projects I had to refactor over 1000 links of VBA that contained “naked” NEXT lines.”

Thanks Alfred.

 

Please note: I reserve the right to delete comments that are offensive or off-topic.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 thoughts on “VBA tip – please don’t leave your Next blank

  1. If you ever have to work with someone elses VBA code that has a great number of blank NEXT lines, consider using NotePad++.
    It support a VB language setting which will indent all the FOR/NEXT sructures for you.
    NotePad++ is freeware and a life saver.
    For one of my projects I had to refactor over 1000 links of VBA that contained “naked” NEXT lines.

  2. The sample code contain a common error.

    Dim i, r, c

    As it stands, these variables are declared as Variant.

    If you really do want to declare them as a Variant, then explicitly state it.