使用基于单元格值的行删除行

时间:2015-11-09 14:16:48

标签: excel vba excel-vba find

我正在尝试在Sheet2中搜索Column A中的Form1中的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

2 个答案:

答案 0 :(得分:0)

以下是代码:

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

    试一试:

    FindNext

答案 1 :(得分:0)

以下是基于THIS

的示例

您不需要循环。您可以使用比循环更快的.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
相关问题