clean way to loop forwards or backwards via variable

RAYLWARD102

Well-known Member
Joined
May 27, 2010
Messages
529
The below example will not work because of the If ASC = statement; Does not allow you to do this when starting a for loop. Any ideas as to how I could do this without duplicating code twice? In my production code, have many procedures inside the loop and would rather edit them once; if I have 2 procedures based on backwards or forwards through loop, I'm editing inside procedures twice. Wish it wasn't necessary to type step -1
Any ways around this ?

Code:
Dim ASC As Boolean
Dim PointA As Long
Dim PointB As Long
List = Split("1,2,3,4,5", ",")
ASC = False
Select Case ASC
    Case True
        PointA = 0
        PointB = UBound(List)
    Case False
        PointA = UBound(List)
        PointB = 0
End Select
If ASC = True Then
    For iCnt = PointA To PointB
Else:
    For iCnt = PointA To PointB Step -1
End If
    
        Debug.Print List(iCnt)
    Next iCnt
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
Simply Dim a variable as Long or Integer (I prefer Long myself) and set it to 1 for forward looping or -1 for backward looping and use it in the Step part of your For statement...

Dim Direction As Long
Direction = -1
For iCnt = PointA to PointB Step Direction
 
Upvote 0

Forum statistics

Threads
1,223,909
Messages
6,175,310
Members
452,634
Latest member
cpostell

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top