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.
Related Posts
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.
Thanks Alfred – you LinkedIn message to me inspired the post. I will add your comment to the bottom of the post.
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.
It isn’t really an error as Variant is the default variable type.
It may be sloppy/lazy coding but not an error.
If you try by selecting hide column and sub sequent column, after selecting them and drag to downwards, all hidden columns will appear.
If you try by selecting hide column and sub sequent column, after selecting them and drag to downwards, all hidden columns will appear. This was tried my self and found it is working.