[英]VBA if cells on sheet 1 match cells on sheet 2 - delete row?
I have two worksheets, sheet 1 and sheet 2. 我有两个工作表,工作表1和工作表2。
On sheet 1 I have created a form which allows users to enter values into cells B21, B26, I21, I26, P21, P26. 在工作表1上,我创建了一个表格,该表格允许用户在单元格B21,B26,I21,I26,P21,P26中输入值。
Then by clicking submit, the data gets inserted onto sheet 2 in columns A,B,C,D,E and F on the next available row. 然后单击提交,将数据插入到下一个可用行的A,B,C,D,E和F列中的工作表2上。
I am also trying to create a macro that once run, will delete the row on sheet 2 where the values match those on sheet1. 我还试图创建一个宏,该宏一旦运行,将删除工作表2上的行,其中值与工作表1上的行匹配。
At the moment i am keeping it simple by using an IF statement, but this gives me a type mismatch error. 目前,我通过使用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
Please can someone show me where i am going wrong? 请有人能告诉我我要去哪里错吗?
First, you need to see if the first condition is met, so we will look for the value in Range("B21") through the entire Column A in Sheets(2)
using the Match
function. 首先,您需要查看是否满足第一个条件,因此我们将使用
Match
函数在Sheets(2)
的整个A列中查找Range(“ B21”)中的值。 If it return a successful match, we will then use that result ( RowMatch
representing a row number). 如果返回成功匹配,则将使用该结果(
RowMatch
代表行号)。
Second, we need to check that all other If
have matching values in RowMatch
in Sheets(2)
. 其次,我们需要检查
Sheets(2)
RowMatch
中所有其他If
是否具有匹配值。 If it does, then we can delete that row in Sheets(2)
. 如果是这样,那么我们可以在
Sheets(2)
删除该行。
Try the code below: 请尝试以下代码 :
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.