Skip to content

Code Inspection for combining multiple For...Next variables on the same line #6249

@IvenBach

Description

What
Combining multiple Next variables as in Next k, j, i is legally valid code, only if each counter variable is listed as shown. Removing the counter variable without each closing Next produces invalid code.

Why
Combining variables into a single Next messes with default indenting. It also can be easily overlooked leading to features bugs. We all strive for clear code.

Example

Public Sub JustBecauseYouCanDoItDoesntMeanYouShould()
    Dim i As Long
    Dim j As Long
    Dim k As Long
    For i = 0 To 9
        For j = 0 To 9
            For k = 0 To 1
                Debug.Print Space(i + j + k) & "But why?"
            Next k, j, i
End Sub

QuickFixes
Insert an ending Next, preferably including the counter variable, to show the ending of each For...Next statement.
Should Rubberduck offer one or more quickfix(es) for this inspection? Describe them here (note: all inspections allow for IgnoreOnceQuickFix, unless explicitly specified):

  1. QuickFix Name - SeparateEachCounterVariableFromACombinedForNextStatementQuickFix

    Example code, after quickfix is applied:

    Public Sub JustBecauseYouCanDoItDoesntMeanYouShould()
        Dim i As Long
        Dim j As Long
        Dim k As Long
        For i = 0 To 9
            For j = 0 To 9
                For k = 0 To 1
                    Debug.Print Space(i + j + k) & "But why?"
                Next k
            Next j
        Next i
    End Sub

Resources
Each inspection needs a number of resource strings - please provide a suggestion here:

  • InspectionNames: MultipleCounterVariablesOnSingleNextEndingStatement
  • InspectionInfo: Combining multiple Next statements visually breaks indenting. It can also lead to overlooking a variables inclusion leading to a subtle bug.
  • InspectionResults: The variables {0} {1} {2} should have their own ending Next statement.

Metadata

Assignees

No one assigned

    Labels

    difficulty-02-duckyResolving these involves the internal API, but with relatively easy problems to solve.enhancementFeature requests, or enhancements to existing features. Ideas. Anything within the project's scope.feature-inspectionsup-for-grabsUse this label in conjunction with a difficulty level label, e.g. difficulty-02-ducky

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions