根据条件删除行,条件是数组

时间:2018-01-26 12:01:36

标签: arrays excel vba

我有2列和300k行

F1  21
F2  32
F3  43
F4  4565
F5  76
F6  76
F7  5
F8  4
F9  4332
…   …

第一列有300个不同的值,我想删除包含特定值的所有行。目前我有;

Sub DeleteRowsBasedOnCondition()
N = Cells(Rows.Count, 1).End(xlUp).Row
For i = N To 1 Step -1
    If Cells(i, 1).Value = "F1" Then Rows(i).Delete
Next i
End Sub

并删除单个联盟(F1),但删除56个条件需要很长时间。

我有一个命名列表toRemove,其中包含我要删除的所有字段。即(F1,F2,F4,F9)。我想引用这个命名列表,而不是56次运行代码。

我想

Sub DeleteRowsBasedOnCondition()
N = Cells(Rows.Count, 1).End(xlUp).Row
For i = N To 1 Step -1
    If Cells(i, 1).Value has a value in the array toRemove
    Then Rows(i).Delete
Next i
End Sub

我尝试了How to search for string in an array帖子,但在引用

行时收到以下错误
function Filter(arr, stringToBeFound):
Run-Time error '13':

Type mismatch

这是我尝试过的代码:

Sub DeleteRowsBasedOnArrayCondition()
' toremove is a named list of values which are to be compared with and deleted from table
N = Cells(Rows.Count, 1).End(xlUp).Row
For i = N To 1 Step -1
    If IsInArray(Cells(i, 2).Value, toremove) Then Rows(i).Delete
Next i
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

1 个答案:

答案 0 :(得分:0)

按照Brainac的建议,我按toRemove列表过滤,然后删除行。

Sub DeleteRowsBasedOnCondition()
For Each i In Worksheets("Sheet2").Range("toRemove")
    Range("a1").Select
    ActiveSheet.Range("$A$1:$c$9").AutoFilter Field:=1, Criteria1:=i
    LR = Cells(Rows.Count, 1).End(xlUp).Row
    Range("A2:A" & LR).SpecialCells(xlCellTypeVisible).Select
    Selection.EntireRow.Delete
Next i
ActiveSheet.ShowAllData

End Sub