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 17 November 2021
Wow! Rick Rothstein Excel MVP added a comment below that blew my mind!
You can combine multiple Next statements into a single statement.
So our example becomes.
Sub ForNextExample4() 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, r, i End Sub
The sequence used is in reverse order – thanks Rick for sharing an amazing technique.
This is not the standard layout, but it is amazing it works.
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.”