Search code examples
excelexcel-2013vba

Optimising For...Next loops in Select Case


I have three different CASEs in a bit of code, each of which has minor variations on a routine revolving around a For...Next loop. The question is, is there any difference in efficiency and speed depending on how I nest them?

In other words, is:

Select Case sPosition
    Case Is = "First"
        For j = 17 to 65
            [Do stuff]
        Next j
    Case Is = "Middle"
        For j = 17 to 65
            [Do stuff]
        Next j
    Case Is = "Last"
        For j = 17 to 65
            [Do stuff]
        Next j
End Select

...any more or less efficient than:

For j = 17 to 65
    Select Case sPosition
        Case Is = "First"
            [Do stuff]
        Case Is = "Middle"
            [Do stuff]
        Case Is = "Last"
            [Do stuff]
    End Select
Next j

Solution

  • More of a question for CodeReview than SO, but regardless, it is dependent on what you are intending to do with the loops. In the first situation, you have a condition and then you loop through the data in accordance with the result of the condition, doing the same thing for all the data. In the second case, you are re-checking the condition each time the loop runs. If you think different things will be happening as the loop runs (different Cases being selected), then you need to use the second variation, but if the checked condition is not changing, then the first option will be faster, as the condition is only checked once for the loop