根据列中的值删除范围内的行

时间:2014-09-24 21:41:30

标签: excel excel-vba delete-row vba

我需要创建一个宏来查看特定列中的每个单元格(即不是整个电子表格)并从特定行开始。然后,它将包含所有不包含我的兴趣值的行。

让我们说例如我的目标是搜索“A”列中的每个值,然后我将从A2过滤到A99999999,保持A1不变。我将删除A列中不包含103526和103527的每一行。

以下代码能够过滤我感兴趣的值的所有行,但是,我只能过滤一列而从A2过滤到A99999999。如何更改此代码以满足这些条件?

Sub test()    
Dim j As Integer, k As Integer    
Dim r As Range, cfind6 As Range, cfind7 As Range    
Worksheets("sheet1").Activate    
On Error Resume Next    
j = Cells(Rows.Count, "A").End(xlUp).Row    
For k = j To 1 Step -1    
Set cfind6 = Rows(k).Cells.Find(what:=103526, lookat:=xlWhole)    

Set cfind7 = Rows(k).Cells.Find(what:=103527, lookat:=xlWhole)    
If cfind6 Is Nothing And cfind7 Is Nothing Then Rows(k).Delete    

Next

1 个答案:

答案 0 :(得分:0)

有几种不同的方法可以解决这个问题,一种方法是将代码更改为:

Sub test()
    Dim i As Integer
    Dim ws As Worksheet

    Set ws = ActiveWorkbook.Sheets("Sheet1")

    For i = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row To 2 Step -1
        If Not (ws.Cells(i, 1).Value = 103526 Or ws.Cells(i, 1).Value = 103527) Then
            ws.Cells(i, 1).EntireRow.Delete
        End If
    Next i
End Sub