简体   繁体   中英

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). 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM