首页 文章

VBA如果工作表1上的单元格与工作表2上的单元格匹配 - 删除行?

提问于
浏览
0

我有两个工作表,第1页和第2页 .

在表1中,我创建了一个表单,允许用户在单元格B21,B26,I21,I26,P21,P26中输入值 .

然后通过单击“提交”,数据将插入到下一个可用行的A,B,C,D,E和F列中的工作表2上 .

我也试图创建一个运行的宏,将删除第2页上的值与sheet1上的值匹配的行 .

目前我通过使用IF语句保持简单,但这给了我一个类型不匹配错误 .

Sub QuickCull()

If Sheets(1).Range("B21").Value = Sheets(2).Range("A:A").Value And _
    Sheets(1).Range("B26").Value = Sheets(2).Range("B:B").Value And _
    Sheets(1).Range("P21").Value = Sheets(2).Range("C:C").Value And _ 
    Sheets(1).Range("I21").Value = Sheets(2).Range("D:D").Value And _
    Sheets(1).Range("I26").Value = Sheets(2).Range("E:E").Value And _
    Sheets(1).Range("P26").Value = Sheets(2).Range("F:F").Value Then

    Rows(ActiveCell.Row).EntireRow.Delete
End If

End Sub

请有人告诉我我哪里出错了?

1 回答

  • 1

    首先,您需要查看是否满足第一个条件,因此我们将使用 Match 函数在 Sheets(2) 中通过整个A列查找Range("B21")中的值 . 如果它返回成功匹配,我们将使用该结果( RowMatch 表示行号) .

    其次,我们需要检查所有其他 IfSheets(2) 中的 RowMatch 中是否具有匹配值 . 如果是,那么我们可以在 Sheets(2) 中删除该行 .

    试试下面的 code

    Option Explicit
    
    Sub QuickCull()
    
    Dim RowMatch As Long
    
    With Sheets(2)
        If Not IsError(Application.Match(Sheets(1).Range("B21").Value, .Range("A:A"), 0)) Then
            RowMatch = Application.Match(Sheets(1).Range("B21").Value, .Range("A:A"), 0)
    
            If Sheets(1).Range("B26").Value = .Range("B" & RowMatch).Value And _
                Sheets(1).Range("P21").Value = .Range("C" & RowMatch).Value And _
                Sheets(1).Range("I21").Value = .Range("D" & RowMatch).Value And _
                Sheets(1).Range("I26").Value = .Range("E" & RowMatch).Value And _
                Sheets(1).Range("P26").Value = .Range("F" & RowMatch).Value Then
    
                .Rows(RowMatch).Delete
            End If
    
        End If
    End With
    
    End Sub
    

相关问题