所以我目前是一个宏,它将一个单元格值赋给变量,然后在另一个工作表上搜索这个变量。问题是我必须执行大量值,因此我目前将相同的代码复制20次,允许20个值进行串行搜索。是否有更清晰的方法来运行这样的可重复操作?也可以根据输入的值的数量设置上限。例如。我当前的设置看起来是M8:M27的变量,是否有可能将其写入以便连续重复直到它碰到空白单元格?从而让用户输入所需数量的值?
以下是单个变量的摘录。然后将其重复到reverse_id_20
Sheets("GR Input").Select
reverse_id_1 = Range("O8")
Sheets("PchOrds").Select
Columns("A:A").Select
Selection.Find(What:=reverse_id_1, After:=ActiveCell, LookIn:= _
xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
xlNext, MatchCase:=False, SearchFormat:=False).Select
Rows(ActiveCell.Row).Select
Selection.Delete Shift:=xlUp
Sheets("GR Input").Select
先谢谢你们, 丹
答案 0 :(得分:0)
是否有更简洁的方法来运行这样的可重复操作?
是的,确实如此。你可以使用循环:
Sub test()
Dim reverse_id As Variant
Dim rng As Range
Dim r_id As Variant
With Sheets("GR Input")
reverse_id = .Range("O8:O11")
End With
For Each r_id In reverse_id
Set rng = Sheets("PchOrds").Columns("A:A").Find( _
What:=r_id, _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False)
If Not rng Is Nothing Then
rng.EntireRow.Delete Shift:=xlUp
End If
Next r_id
End Sub
顺便说一句,上面的代码只删除符合条件的第一行。如果您要删除符合条件的工作表“PchOrds”中的所有值,请使用以下代码:
Sub test1()
Dim reverse_id As Variant
Dim rng As Range
Dim lastrow As Long
Dim r_id As Variant
With Sheets("GR Input")
reverse_id = .Range("O8:O11")
End With
For Each r_id In reverse_id
If r_id <> "" Then
With Sheets("PchOrds")
lastrow = Application.Max(2, .Cells(.Rows.Count, "A").End(xlUp).Row)
.AutoFilterMode = False
With .Range("A1:A" & lastrow)
.AutoFilter Field:=1, Criteria1:="=*" & r_id & "*"
.Offset(1, 0).Resize(lastrow - 1, 1).EntireRow.Delete
End With
.AutoFilterMode = False
End With
End If
Next r_id
End Sub