[英]Loop through sheet 1 and sheet 2 for column A if value matches delete the entire row in sheet 1
I have Sheet 1 (Column A ) value and Sheet 2 (Column A).我有工作表 1(A 列)值和工作表 2(A 列)。 I want to compare sheet 1 column A with sheet 2 Column A. If Sheet 1 (Column A) is found in the Sheet 2 then Delete the entire row in the Sheet 1. go to next one.我想将工作表 1 的 A 列与工作表 2 的 A 列进行比较。如果在工作表 2 中找到工作表 1(A 列),则删除工作表 1 中的整行。go 到下一个。
I have been stuck on this.我一直坚持这一点。 Below is my Code.下面是我的代码。 Its not working.它不工作。 Its keep getting wrong cell values它不断得到错误的单元格值
Sub Compare()
Dim i As Long
Dim j As Long
Dim lastRow_Task As Long
Dim lastRow_Compare As Long
Dim lastRow As Long
'Sheet 1
Dim Task As Worksheet
'Sheet 2
Dim Compare As Worksheet
Set Task = Excel.Worksheets("TaskDetails")
Set Compare = Excel.Worksheets("Compare")
Application.ScreenUpdating = False
lastRow_Task = Log.Cells(Rows.count, "A").End(xlUp).Row
lastRow_Compare = Compare.Cells(Rows.count, "A").End(xlUp).Row
For i = 2 To lastRow_Task
For j = 2 To lastRow_Compare
If Task.Cells(i, "A").Value = Compare.Cells(j, "A").Value Then
Compare.Cells(j, "A").ClearContents
End If
Next j
Next i
Using Match() is fast and will avoid the nested loop.使用 Match() 速度很快,并且可以避免嵌套循环。
Also - when deleting rows it's best to work from the bottom to the top so the deleted rows don't interfere with your loop counter.另外 - 删除行时,最好从底部到顶部工作,这样删除的行就不会干扰您的循环计数器。
Sub Compare()
Dim i As Long
Dim lastRow_Task As Long
Dim Task As Worksheet 'Sheet 1
Dim Compare As Worksheet 'Sheet 2
Set Task = ActiveWorkbook.Worksheets("TaskDetails")
Set Compare = ActiveWorkbook.Worksheets("Compare")
Application.ScreenUpdating = False
lastRow_Task = Task.Cells(Task.Rows.Count, "A").End(xlUp).Row
For i = lastRow_Task To 2 Step -1
If Not IsError(Application.Match(Task.Cells(i, 1).Value, Compare.Columns(1), 0)) Then
Task.Rows(i).Delete
End If
Next i
Application.ScreenUpdating = True
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.