![](/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.