Excel 如果没有匹配的表2,则删除行表1。不同数量的标题
我发现了这个VBA,我希望它在图纸2上找不到它时删除图纸1上的行。但是,我在表2中有1行标题,在表1中有2行标题。只有当两张表都有一个行标题时,我才能得到代码。你们谁能告诉我我做错了什么( 你可以试试这个:Excel 如果没有匹配的表2,则删除行表1。不同数量的标题,excel,vba,Excel,Vba,我发现了这个VBA,我希望它在图纸2上找不到它时删除图纸1上的行。但是,我在表2中有1行标题,在表1中有2行标题。只有当两张表都有一个行标题时,我才能得到代码。你们谁能告诉我我做错了什么( 你可以试试这个: Option Explicit Sub DeleteNotMatch22() Dim ws1 As Worksheet, ws2 As Worksheet Dim r1 As Long, r2 As Long, i As Long 'Set worksheet
Option Explicit
Sub DeleteNotMatch22()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim r1 As Long, r2 As Long, i As Long
'Set worksheets
With ThisWorkbook
Set ws1 = .Sheets("Sheet1")
Set ws2 = .Sheets("Sheet2")
End With
'Find Last rows
r1 = ws1.cells(ws1.Rows.Count, "A").End(xlUp).Row
r2 = ws2.cells(ws2.Rows.Count, "A").End(xlUp).Row
'Loop sheet 1, column A starting from the botton to top up to row 3
For i = r1 To 3 Step -1
'If the value of sheet 1, column A row i appears sheet 2 range A2:A lastrow
If Application.WorksheetFunction.CountIf(ws2.Range("A2:A" & r2), ws1.Range("A" & i).Value) = 0 Then
ws1.Rows(i).Delete
End If
Next i
End Sub
欢迎来到SO。这里有一些友好的建议:逐步完成(F8)你的代码-找出它选择的位置。你可能只需要一个
-1
。阅读代码的作用并根据需要调整它。你的x=
正在拉取Sheet1
中所有行的匹配,然后相交
从上面拉取使用的范围。为什么不尝试将UsedRange
更改为som什么是你可以操纵的?谢谢你的建议。我试着一步一步地做,但我真的找不到解决办法。你会把-1放在哪里?
Option Explicit
Sub DeleteNotMatch22()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim r1 As Long, r2 As Long, i As Long
'Set worksheets
With ThisWorkbook
Set ws1 = .Sheets("Sheet1")
Set ws2 = .Sheets("Sheet2")
End With
'Find Last rows
r1 = ws1.cells(ws1.Rows.Count, "A").End(xlUp).Row
r2 = ws2.cells(ws2.Rows.Count, "A").End(xlUp).Row
'Loop sheet 1, column A starting from the botton to top up to row 3
For i = r1 To 3 Step -1
'If the value of sheet 1, column A row i appears sheet 2 range A2:A lastrow
If Application.WorksheetFunction.CountIf(ws2.Range("A2:A" & r2), ws1.Range("A" & i).Value) = 0 Then
ws1.Rows(i).Delete
End If
Next i
End Sub