我有多个文本变量(水果),当它们出现在R列时,我需要删除整行。我有以下代码,但由于我有15个“Fruit”变量(并且可能需要在将来添加更多),我想知道如何才能使这是一个带循环的单个子程序。我尝试了许多失败的方法。可能有一个包含所有名字的字符串数组?
提前致谢,
Sub Fix1()
Dim Fruit As String
Fruit = "Apple"
Do
On Error GoTo ByeBye
Range("R:R").Find(Fruit).EntireRow.Delete
Loop
ByeBye:
Exit Sub
End Sub
Sub Fix2()
Dim Fruit As String
Fruit = "Orange"
Do
On Error GoTo ByeBye
Range("R:R").Find(Fruit).EntireRow.Delete
Loop
ByeBye:
Exit Sub
End Sub
答案 0 :(得分:2)
您可以使用AutoFiter()
:
Sub FixAll()
Dim Fruits As Variant
Fruits = Array("Apple", "Banana", "Pear") '<--| list your fruits
With Range("R:R") '<--| reference your range
.AutoFilter Field:=1, Criteria1:=Fruits, Operator:=xlFilterValues '<--| filter referenced column with 'Fruits'" content
If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete '<--| if any cell found other than header one then delete its corresponding row
End With
ActiveSheet.AutoFilterMode = False
End Sub
答案 1 :(得分:0)
如果您不需要删除第一行:
Dim r As Range
Set r = ActiveSheet.UsedRange
r.AutoFilter 19 - r.Column, Array("Apple", "Orange"), xlFilterValues
r.Offset(1).Delete xlShiftUp ' deletes the non-filtered rows
r.AutoFilter ' hide the filter