Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

vba - Loop through Excel Sheets

I have the following Code and I would like it to run in 25 other sheets of the Workbook and instead of repeating the code 25 times,for each sheet is there a way to make it loop?

Can someone assist?

Sub DeleteEmptyRows()
Dim ws As Worksheet
Dim strSearch As String
Dim lRow As Long

strSearch = "ressort"

Set ws = Sheets("01,02,03")

With ws
    lRow = .Range("A" & .Rows.Count).End(xlUp).Row




    With .Range("A1:A" & lRow)
      .AutoFilter Field:=1, Criteria1:="=*" & strSearch & "*"
      .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

   ActiveSheet.Range("$A$1:$P$65536").AutoFilter Field:=1

End With
End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Wrap the processing code in a loop

for each ws in thisworkbook.sheets
    ' do something on each worksheet
next

example

Sub DeleteEmptyRows()
    Dim ws As Worksheet
    Dim strSearch As String
    Dim lRow As Long

    strSearch = "ressort"

    For Each ws In ThisWorkbook.Sheets
        If (ws.Name <> "Sheet1") And (ws.Name <> "Sheet2") And (ws.Name <> "Sheet3") Then
            With ws
            lRow = .Range("A" & .Rows.Count).End(xlUp).Row
                With .Range("A1:A" & lRow)
                  .AutoFilter Field:=1, Criteria1:="=*" & strSearch & "*"
                  .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
                End With
                ws.Range("$A$1:$P$65536").AutoFilter Field:=1
            End With
        End If
    Next
End Sub

so now if the sheet names are Sheet1 or Sheet2 or Sheet3 they will be skipped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...