基于搜索关键字VBA删除行

时间:2012-11-28 21:47:32

标签: excel excel-vba vba

我正在尝试删除使用VBA在B列中找到值“X”的每个行。但是,我有三个问题:

  1. 我无法使用cells.find方法将我的VBA代码从活动单元格下移到下一个单元格(B3)(参见下面的代码)
  2. 我的代码不会删除在B列中找到值“X”的整行。
  3. B栏中的数据量可能会有所不同:它可以在今天的B10结束,或明天的B100结束(见下面的屏幕截图)
  4. 非常感谢任何帮助。

    Sub RemoveRows()   
        Dim strLookFor As String
        Dim strRow As String
    
        Worksheets("Sheet1").Range("B2").Activate
    
        strLookFor = "X"
        strRow = Range("B2").Address
    
        Do Until ActiveCell.Value = ""        
            MsgBox (ActiveCell.Value)        
            If ActiveCell.Value = strLookFor Then
                Rows.Delete (strRow)
            End If            
            strRow = Cells.Find(what:=strLookFor).Address
        Loop
    
        MsgBox ("Deleted all rows with value " & strLookFor)    
    End Sub
    

    enter image description here

3 个答案:

答案 0 :(得分:6)

使用AutoFilter比范围循环

更有效
Sub QuickCull()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Sheets("Sheet1")
Set rng1 = ws.Range(ws.[b2], ws.Cells(Rows.Count, "B").End(xlUp))
Application.ScreenUpdating = False
With ActiveSheet
        .AutoFilterMode = False
        rng1.AutoFilter Field:=1, Criteria1:="X"
        rng1.Offset(1, 0).EntireRow.Delete
        .AutoFilterMode = False
    End With
Application.ScreenUpdating = True
End Sub

答案 1 :(得分:2)

dim x as long
dim r as long
dim sht as worksheet

set sht = Worksheets("Sheet1")
r = sht.Cells(rows.count,2).end(xlup).row 

for x = r to 2 step -1
    with sht.cells(x,2)
        if .value = "X" then .entirerow.delete
    end with 
next x

答案 2 :(得分:1)

这应该有效:

Sub DeleteRowsWithX()

maxRow = ActiveSheet.UsedRange.Rows.Count

For i = 1 To maxRow
    Do While (StrComp(ActiveSheet.Cells(i, 2).Text, "X", vbTextCompare) = 0)
        Rows(i).Select
        Selection.Delete Shift:=xlUp
   Loop
Next

End Sub