Search code examples
excelvbafor-loopworksheet

For i = 2 to thisworkbook.worksheets.count through all the worksheets in a workbook


Can anyone help me out? I am trying to make my code loop through all the worksheets in a workbook. It does perfectly for the one worksheet, but I am struggling to make it loop through all the worksheets

    Sub stringcheck()

Dim MainString As String
Dim SubString As String
Dim Lastrow As Long, Lcount As Long
Dim i As Integer, j As Integer

SubString = "All Grps"

Lastrow = ThisWorkbook.Worksheets("SalesChannelName").Range("A30000").End(xlUp).Row


For i = 3 To Lastrow
    MainString = Range("B" & i)
        If InStr(MainString, SubString) <> 0 Then
            Rows(Range("A" & i).Row + 1 & ":" & Range("A" & i).Row + 2).Insert
        End If
Next i

End Sub

Solution

  • You may give this a try...

    Sub stringcheck()
        Dim ws As Worksheet
        Dim MainString As String
        Dim SubString As String
        Dim Lastrow As Long, Lcount As Long
        Dim i As Integer, j As Integer
    
        Application.ScreenUpdating = False
    
        SubString = "All Grps"
    
        For Each ws In ActiveWorkbook.Worksheets
            Lastrow = ws.Cells(Rows.Count, 1).End(xlUp).Row
            For i = Lastrow To 3 Step -1
                MainString = ws.Range("B" & i)
                If InStr(MainString, SubString) <> 0 Then
                    ws.Range("A" & i + 1).Resize(2).EntireRow.Insert
                End If
            Next i
        Next ws
        Application.ScreenUpdating = True
    End Sub