根据单元格值删除行

我正在试图在Sheet2中的Sheet A中searchSheet1中A1的值。

如果存在,我想删除Sheet2中的整个行。

如果它不存在,我想要打开消息框。


这是我所拥有的,但我正在努力实际删除该行:

Sub Delete_Rows() Dim FindString As String Dim Rng As Range FindString = Sheets("Sheet1").Range("A1") If Trim(FindString) <> "" Then With Sheets("Sheet2").Range("A:A") Set Rng = .Find(What:=FindString, _ After:=.Cells(.Cells.Count), _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) If Not Rng Is Nothing Then 'I can't figure out how to delete the row Else MsgBox "Not Found" End If End With End If End Sub 

这里是一个基于这个例子

你不需要循环。 您可以使用比循环更快的自动.Autofilter

 Sub Sample() Dim ws1 As Worksheet, ws2 As Worksheet Dim delRange As Range Dim lRow As Long Dim strSearch As String Set ws1 = Sheet1: Set ws2 = Sheet2 strSearch = ws1.Range("A1").Value With ws2 '~~> Remove any filters .AutoFilterMode = False lRow = .Range("A" & .Rows.Count).End(xlUp).Row With .Range("A1:A" & lRow) .AutoFilter Field:=1, Criteria1:="=" & strSearch Set delRange = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow End With '~~> Remove any filters .AutoFilterMode = False End With If delRange Is Nothing Then MsgBox "Not Found" Else delRange.Delete End If End Sub 

这里是代码来:

  1. 循环遍历Sheet1的A列中的所有值,
  2. 在工作表2的列A中查找所有匹配(使用FindNext方法)
  3. 并删除相匹配的行

试一试 :

 Sub test_user5472539() Dim Ws1 As Worksheet, _ Ws2 As Worksheet, _ LastRow As Long, _ FindString As String, _ FirstAddress As String, _ cF As Range Set Ws1 = ActiveWorkbook.Sheets("Sheet1") Set Ws2 = ActiveWorkbook.Sheets("Sheet2") LastRow = Ws1.Range("A" & Ws1.Rows.Count).End(xlUp).Row For i = 1 To LastRow FindString = Ws1.Range("A" & i) If Trim(FindString) <> "" Then Ws2.Range("A1").Activate With Ws2.Range("A:A") 'First, define properly the Find method Set cF = .Find(What:=FindString, _ After:=.Cells(1, 1), _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) 'If there is a result, keep looking with FindNext method If Not cF Is Nothing Then FirstAddress = cF.Address Do cF.EntireRow.Delete Set cF = .FindNext(cF) 'Look until you find again the first result Loop While Not cF Is Nothing And cF.Address <> FirstAddress Else MsgBox "Not Found" End If End With Else End If Next i End Sub