我正在尝试应用此代码但由于某种原因它不起作用,任何人都可以帮我修复它吗?它应删除包含特定文本的行,并将其应用于工作簿中的所有工作表。当我尝试此代码时,它只适用于一个工作表。显然,删除代码的行部分有效,但不适用于应该应用于所有工作表的循环。
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
答案 0 :(得分: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
以上工作原理是将Worksheet Index属性与您创建的n
变量一起使用。
答案 1 :(得分:5)
尝试下面的代码,使用With ws
语句来测试相关表格中的所有行。
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
答案 2 :(得分:1)
您必须在范围操作中指定工作表,否则它将在每次迭代中与ActiveSheet一起使用。
Sub WorksheetLoop()
Dim c As Integer
Dim n As Integer
c = ActiveWorkbook.Worksheets.Count
For n = 1 To c Step 1
Last = Sheets(n).Cells(Rows.Count, "A").End(xlUp).Row
For I = Last To 1 Step -1
If (Sheets(n).Cells(I, "A").Value) = "Text" Then
Sheets(n).Cells(I, "A").EntireRow.Delete
End If
Next I
Next n
End Sub
答案 3 :(得分:0)
尝试使用它。这几乎和Shai的答案一样,但是我激活了每个工作表。 (下一个工作表不会在“对于每个人”中自动激活;您必须在每个步骤中手动将其激活)
Dim ws As Worksheet
'Walk through each worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Activate
'Add your code here
Next ws