Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

excel - Delete Row based on Search Key VBA

I am trying to delete every row in which the value "X" is found in column B using VBA. However, I'm having three problems:

  1. I can't get my VBA code to move down from the active cell to the next cell (B3) using cells.find method (see code below)
  2. My code does not delete the entire row where the value "X" is found in column B
  3. The amount of Data in Column B can vary: it can end at B10 today, or B100 tomorrow (see screen shot below)

Any assistance will be greatly appreciated.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using an AutoFilter is much more efficient than a range loop

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...