如何将VBA代码应用于工作簿中的所有工作表

Rov*_*yev 3 excel vba

我正在尝试应用此代码但由于某种原因它不起作用,任何人都可以帮我修复它吗?它应删除包含特定文本的行,并将其应用于工作簿中的所有工作表.当我尝试此代码时,它只适用于一个工作表.显然,删除代码的行部分有效但不应该应用于所有工作表的循环.

Sub WorksheetLoop()

     Dim c As Integer
     Dim n As Integer
     c = ActiveWorkbook.Worksheets.Count
     For n = 1 To c Step 1
        Last = Cells(Rows.Count, "A").End(xlUp).Row
        For I = Last To 1 Step -1
            If (Cells(I, "A").Value) = "Text" Then
                Cells(I, "A").EntireRow.Delete
            End If
        Next I
     Next n

 End Sub
Run Code Online (Sandbox Code Playgroud)

Sco*_*man 7

它不起作用,因为您从未限定要在代码中使用的工作表.简单的修复,主要保持您的代码如下.

Sub WorksheetLoop()

 Dim c As Integer
 Dim n As Integer
 c = ActiveWorkbook.Worksheets.Count
 For n = 1 To c Step 1
    Last = Worksheets(n).Cells(Rows.Count, "A").End(xlUp).Row
    For I = Last To 1 Step -1
        If (Worksheets(n).Cells(I, "A").Value) = "Text" Then
            Worksheets(n).Cells(I, "A").EntireRow.Delete
        End If
    Next I
 Next n

 End Sub
Run Code Online (Sandbox Code Playgroud)

上面的工作原理是将Worksheet Index属性与n您创建的变量一起使用.


Sha*_*ado 5

尝试下面的代码,使用With wsstatement来测试相关表中的所有行.

Option Explicit

Sub WorksheetLoop()

Dim i As Long
Dim ws As Worksheet
Dim Last As Long

' loop through all worksheets
For Each ws In ThisWorkbook.Worksheets
    With ws
        Last = .Cells(.Rows.Count, "A").End(xlUp).Row
        For i = Last To 1 Step -1
            If (.Cells(i, "A").Value) = "Text" Then
                .Cells(i, "A").EntireRow.Delete
            End If
        Next i
    End With
Next ws

End Sub
Run Code Online (Sandbox Code Playgroud)