您需要通过添加.
作为前缀完全限定所有Range
和Cells
的With WS
语句中。
E.g.而不是pattern = Cells(10, 2)
使用pattern = .Cells(10, 2)
,.Cells(10, 2)
意味着WS
的单元格(10,2),它在For Each WS In ThisWorkbook.Worksheets
中正在进行中。
代码
Option Explicit
Sub Deletrows_Click()
Dim WS As Worksheet
Dim pattern As String
Dim RowCount As Long, i As Long, j As Long
For Each WS In ThisWorkbook.Worksheets
With WS
pattern = .Cells(10, 2) ' delete row if found the word total in it
RowCount = .UsedRange.Rows.Count
For i = 2 To RowCount
For j = 1 To 3 'find the word within this range
If .Cells(i, j) = pattern Then
.Cells(i, j).EntireRow.Delete
End If
Next j
Next i
End With
Next WS
End Sub
选项2:不要使用两个For
循环,你可以用Application.Match
功能取代第二For
循环,以寻找一个特定值在整个行。与之相匹配的
Option Explicit
Sub Deletrows_Click()
Dim WS As Worksheet
Dim pattern As String
Dim RowCount As Long, i As Long, j As Long
For Each WS In ThisWorkbook.Worksheets
With WS
pattern = .Cells(10, 2) ' delete row if found the word total in it
RowCount = .UsedRange.Rows.Count
For i = 2 To RowCount
' use the Match function to find the word inside a certain row
If Not IsError(Application.Match(pattern, .Range(.Cells(i, 1), .Cells(i, 3)), 0)) Then '<-- match was successful
.Cells(i, 1).EntireRow.Delete
End If
Next i
End With
Next WS
End Sub
编辑
代码2:
Option Explicit
Sub Deletrows_Click()
Dim WS As Worksheet
Dim pattern As String
Dim FirstRow As Long, RowCount As Long, i As Long, j As Long
Dim FirstCol, ColCount As Long
For Each WS In ThisWorkbook.Worksheets
With WS
pattern = .Cells(10, 2) ' delete row if found the word total in it
FirstRow = .UsedRange.Row
RowCount = .UsedRange.Rows.Count
FirstCol = .UsedRange.Column
ColCount = .UsedRange.Columns.Count
For i = 2 To RowCount + FirstRow
' use the Match function to find the word inside a certain row
If Not IsError(Application.Match(pattern, .Range(.Cells(i, 1), .Cells(i, ColCount + FirstCol)), 0)) Then '<-- match was successful
.Cells(i, 1).EntireRow.Delete
End If
Next i
End With
Next WS
End Sub
非常感谢夏嘉曦的善意帮助,它帮助了很多 –