![](/img/trans.png)
[英]Excel VBA for hiding cells in one sheet if they match cells in another sheet
[英]VBA if cells on sheet 1 match cells on sheet 2 - delete row?
我有两个工作表,工作表1和工作表2。
在工作表1上,我创建了一个表格,该表格允许用户在单元格B21,B26,I21,I26,P21,P26中输入值。
然后单击提交,将数据插入到下一个可用行的A,B,C,D,E和F列中的工作表2上。
我还试图创建一个宏,该宏一旦运行,将删除工作表2上的行,其中值与工作表1上的行匹配。
目前,我通过使用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
请有人能告诉我我要去哪里错吗?
首先,您需要查看是否满足第一个条件,因此我们将使用Match
函数在Sheets(2)
的整个A列中查找Range(“ B21”)中的值。 如果返回成功匹配,则将使用该结果( RowMatch
代表行号)。
其次,我们需要检查Sheets(2)
RowMatch
中所有其他If
是否具有匹配值。 如果是这样,那么我们可以在Sheets(2)
删除该行。
请尝试以下代码 :
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.