Excel VBA过滤和删除

时间:2018-06-18 14:58:37

标签: excel-vba filter vba excel

我搜索了论坛,但却找不到真正有用的东西。我有一个简单的工作表,我想过滤任何标有" LOW"或者" TBD"并删除那些。然后删除过滤器。

我正在运行以下代码,但由于它删除了每个代码,因此我会错过一些代码,因为我会继续这样做。

For i = 2 To access.UsedRange.Rows.Count

If access.Cells(i, 11) = "LOW" Or "TBD" Then
Rows(i).delete
Exit For
End If

Next i

4 个答案:

答案 0 :(得分:2)

If access.Cells(i, 11) = "LOW" Or  access.Cells(i, 11) = "TBD" Then

或者如果你想变得更加漂亮:

With access.Cells(i, 11)
    If .Value2 = "LOW" Or .Value2 = "TBD" Then Rows(i).Delete
End With

每当删除行时,这是最佳做法:

For i = access.UsedRange.Rows.Count to 2 Step -1

如果速度有点慢,请考虑将行添加到Union()的范围并删除整个范围。我应该Union()应该是最快的解决方案 - How do I ignore the first row in an Excel macro that deletes all rows based on a criteria?

答案 1 :(得分:1)

如果要删除Excel中某个范围内的记录,并使用行号引用行,则应从底部开始,然后按照自己的方式进行操作。原因是当你检查第5行并删除它时,第6行现在变为第5行,但是你的循环计数器增加到第7行 - 因此你永远不会检查第6行。

我建议:

Dim LastRow as Long

LastRow = access.UsedRange.Rows.Count
For i = LastRow To 2 Step - 1
    If access.Cells(i, 11) = "LOW" Or "TBD" Then
        Rows(i).delete
    End If
Next i

答案 2 :(得分:0)

玩具可以这样试试。为什么你为列索引添加11。 AZ是指数50

Sub test2()


' Active workbook
Dim wb As Workbook
Set wb = ThisWorkbook
Dim i As Long


'*******************************************
'Adapt this vars


'define your sheets
Dim ws_1 As Worksheet
Set ws_1 = wb.Sheets("Feuil1")

'definie the last Rows
Dim lastRow_ws1 As Long

lastRow_ws1 = ws_1.Range("AZ" & Rows.Count).End(xlUp).Row
'*******************************************


For i = lastRow_ws1 To 2 Step -1

    Dim keySearch As String
    keySearch = ws_1.Cells(i, 50).Value

    If keySearch = "LOW" Or keySearch = "TBD" Then
    ws_1.Rows(i).EntireRow.Delete
    End If


Next i

End Sub

答案 3 :(得分:0)

这是一个使用AutoFilter而不是逐行遍历行的版本。作为警告,此清除您对数据的所有过滤器。 (除非你有保存/恢复过滤器的宏)

Const FilterColumn = 52 ' Column AZ

'Clear Filters
access.AutoFilterMode = False
'Filter for data
access.UsedRange.AutoFilter FilterColumn, "LOW", xlOr, "TBD"
'If Data exists
If access.Cells(access.Rows.Count, FilterColumn).End(xlUp).Row > 1 Then
    'Delete visible rows
    access.Range(access.Cells(2, FilterColumn), access.Cells(access.Rows.Count, FilterColumn)).EntireRow.Delete
End If
'Clear Filters
access.AutoFilterMode = False