2012-11-28 60 views
2

我試圖刪除行,其中在列B中使用VBA找到值「X」。但是,我有三個問題:根據搜索關鍵字刪除行VBA

  1. 我不能讓我的VBA代碼從活動單元格向下移動到使用cells.find方法下一個單元格(B3)(請參見下面的代碼)
  2. 我的代碼並不刪除在列B中找到值「X」的整行
  3. 列B中的數據量可能有所不同:它可以在今天的B10或明天的B100結束(參見下面的屏幕截圖)

任何援助將不勝感激。

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

回答

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

+1哇。確實非常有效。 – Anthony

+0

AutoFilter非常有趣。我正在研究它。非常感謝! – Anthony

+0

我對這個主題很感興趣,你能否向我解釋這兩條線是做什麼的? 1-'Set rng1 = ws.Range(ws。[b2],ws.Cells(Rows.Count,「B」)。End(xlUp))'和2-'rng1.Offset(1,0).EntireRow。 Delete'。 –

0

這應該工作:

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 
+2

我建議通過倒退更有效行。正如你現在所做的那樣,它會錯過是否有連續的兩行'X'在其中 – SeanC

+1

這將無法正常工作。如果連續的行有「X」,那麼它將跳過每隔一行刪除一行。 –

+0

感謝您的提示。更正 – David

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 
+0

+1謝謝,效果很棒! – Anthony