VBA code for cycling through worksheets starting with a specific sheet (index 3)

I need to iterate over sheets with index 3 on the last sheet and run the code. I tried something like this, but its not working.

If (ws.sheetIndex > 2) Then
        With ws
            'code goes here
        End With
End If

I did a search but could not find a solution to this problem. Help would be greatly appreciated.

I also tried:

Dim i As Long, lr As Long
Dim ws As Worksheet
Windows("Book1").Activate

With ActiveWorkbook
    Set ws = .Worksheets("index")
    For i = 3 To 10
        'code goes here
    Next i


End With
+4
source share
3 answers

You can try the following, which iterates over all sheets in your book and only "acts" for sheets with index 3 or higher.

Dim sheet As Worksheet

For Each sheet In ActiveWorkbook.Worksheets
  If sheet.Index > 2 Then
    ' Do your thing with each "sheet" object, e.g.:
    sheet.Cells(1, 1).Value = "hi"
  End If
Next

, , (10 - ), .


, "Sheet" + i ( i - 3- ), :

Dim sheet As Worksheet
Dim i As Long

For i = 3 To ActiveWorkbook.Worksheets.Count
  Set sheet = ActiveWorkbook.Worksheets(i)
  If sheet.Name = "Sheet" & i Then
    ' Do your thing with each "sheet" object, e.g.:
    sheet.Cells(2, 2).Value = "hi"
  End If
Next i

, , , . , , , .

+6

, Worksheets, CodeName ( ) CodeName , :

Public Sub TestLoop()
    On Error GoTo ErrHandler
    Dim ws As Worksheet, s As String
    For Each ws In Worksheets
        If ws.CodeName <> "Sheet2" Then
            s = s & vbNewLine & ws.CodeName
        End If
    Next ws

    s = "WorksheetList (except Sheet2:" & vbNewLine & vbNewLine & s

    MsgBox s, vbOKOnly, "Test"
EndSUb:
    Exit Sub
ErrHandler:
    Resume EndSUb
End Sub

3, Sheet1, MsgBox:

WorksheetList (except Sheet2:

Sheet3
Sheet1
+1

Try to exclude the first and second sheets using the name:

Public Sub Sheets3andUp()
Dim ws As Worksheet
Dim nameOfSheet1 As String
Dim nameOfSheet2 As String

nameOfSheet1 = "Sheet1"
nameOfSheet2 = "Sheet2"

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name <> nameOfSheet1 And ws.Name <> nameOfSheet2 Then
        'Code goes here
        Debug.Print ws.Name
    End If
Next ws

End Sub

+1
source

All Articles