hieppm
hieppm

Reputation: 113

Is this line a unnecessary line in VBA?

This is a sample for loop in VBA of excel.

Sub Tests ()

Dim a As Integer
Dim b As Integer

b = 5

For a = 1 to b 
    MsgBox a
Next a  

End Sub 

When I remove a in Next a, the script still run normally. So why do we have to have Next a rather than Next?

Upvotes: 1

Views: 92

Answers (3)

AMissico
AMissico

Reputation: 21684

Simply put, old BASIC versions required the use, such as GW-BASIC. Newer BASIC versions, such as QuickBASIC, kept the syntax to support older code for backward compatibility. Today, with the Visual versions of BASIC, such as VBScript, VBA, and Visual BASIC, it seems odd that you would have to specify the loop variable, since they can infer where the loop ends.

I think you will find over time, that you will drop the Next <variable> syntax. There is no value add for its use and makes maintenance a little harder because if you change the variable in the For statement, you will have to change it in the Next statement.

Yet, due to BASIC's interpreter nature, there are times where you need to specify which Next statement applies. In all of my many years of BASIC programming, I used this technique more in the early days and rarely in modern times because of newer features of the language.

Upvotes: 0

Stepan1010
Stepan1010

Reputation: 3136

See the Technical Implementation section of documentation about For...Next Statement (Visual Basic) from Microsoft: http://msdn.microsoft.com/en-us/library/5z06z1kb.aspx

If you nest loops, the compiler signals an error if it encounters the Next statement of an outer nesting level before the Next statement of an inner level. However, the compiler can detect this overlapping error only if you specify counter in every Next statement.

So it is better to be more specific and specify which counter you are incrementing/decrementing because it helps the compiler detect errors in nested loops. But it is certainly not necessary in all loops - it is optional.

Microsoft recommends it for readability as well in the Counter Argument section of the same page:

You can optionally specify the counter variable in the Next statement. This syntax improves the readability of your program, especially if you have nested For loops. You must specify the variable that appears in the corresponding For statement.

Upvotes: 3

MLDev
MLDev

Reputation: 1277

Is it necessary? No. Should you use it. Personally I'd say yes. In larger codes you might have multiple nested loops. Maybe 100s of lines between the lines

For a = 1 to b 

and the line

Next

Therefore, adding the a after next would really help determine where the loop is starting and ending.

Upvotes: 1

Related Questions