How can I loop through a subset of worksheets?

Kirk Hings picture Kirk Hings · Oct 20, 2009 · Viewed 44k times · Source

I know how to loop through all the worksheets in a workbook, and how to exit once I reach an 'end-flag' worksheet:

For Each ThisWorkSheet In Worksheets
   If ThisWorkSheet.Name = "FlagEnd" Then Exit For
   MsgBox "This worksheet name is: " & ThisWorkSheet.Name
Next

However I cannot get the loop to begin on a 'start-flag' worksheet (or even better on the worksheet right after the start-flag worksheet. For example the flagged start/end worksheets are in the middle of a bunch of other worksheets, so beginning or end traversing is not workable.

There could be hundreds of worksheets before that 'FlagStart' sheet, so I really need to start on the right sheet.

Tried:

Set ThisWorkSheet = Sheets("FlagNew")

and

For Each Sheets("FlagNew") In Worksheets

Ideas?

Solution: Mathias was very close, but dendarii was that tiny step closer with the custom ending index. I actually figured out my final solution on my own, but wanted to give credit. Here was my final solution:

Private Sub CommandButtonLoopThruFlaggedSheets_Click()
    ' determine current bounds
    Dim StartIndex, EndIndex, LoopIndex As Integer
    StartIndex = Sheets("FlagNew").Index + 1
    EndIndex = Sheets("FlagEnd").Index - 1

    For LoopIndex = StartIndex To EndIndex
        MsgBox "this worksheet is: " & Sheets(LoopIndex).Name
        ' code here
    Next LoopIndex
End Sub

Answer

Mathias picture Mathias · Oct 20, 2009

I believe that if you use "foreach" you won't have any control over the starting sheet. For that matter, I am not even sure you are guaranteed the order in which the iteration will take place.
I think what you should do is first, get the index of the sheet you are interested in (get the sheet by name, and get its index), and then iterate using a for loop, over the indexes of the sheets starting at the flag sheet index.
[Edit: I hacked through a quick example]

Sub Iterate()

Dim book As Workbook
Dim flagIndex As Integer
Dim flagSheet As Worksheet

Set book = ActiveWorkbook
Set flagSheet = book.Worksheets("Sheet3")
flagIndex = flagSheet.Index

Dim sheetIndex As Integer
Dim currentSheet As Worksheet

For sheetIndex = flagIndex To book.Worksheets.Count
    Set currentSheet = book.Worksheets(sheetIndex)
Next

End Sub