Nested loop

Brutusar

Board Regular
Joined
Nov 23, 2019
Messages
166
Office Version
  1. 365
Platform
  1. Windows
Hi, I have two Sheets, 1 and 2. Both have two columns with values, A and B. Both of these may have several thousands of rows. I need to compare these two sheets to find rows that are present in Sheet1 but not in Sheet2.

I have written a code for this, but as it takes forever to run without doing very much I guess there is at least one major mistake in the code. Anyone have time to have a quick look and give me a hint in the right direction?



VBA Code:
Sub FindMissingValues()
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim ws3 As Worksheet
    Dim range1 As Range
    Dim range2 As Range
    Dim cell As Range
    Dim found As Boolean
    
    ' Set the worksheets
    Set ws1 = ThisWorkbook.Sheets("Sheet1")
    Set ws2 = ThisWorkbook.Sheets("Sheet2")
    Set ws3 = ThisWorkbook.Sheets("Sheet3")
    
    ' Set the ranges to loop through
    Set range1 = ws1.Range("A:B")
    Set range2 = ws2.Range("A:B")
    
    ' Loop through each cell in Sheet1 range "A:B"
    For Each cell In range1
        ' Reset found flag
        found = False
        
        ' Loop through each cell in Sheet2 range "A:B"
        For Each c In range2
            ' Check if the value in Sheet1 is present in Sheet2
            If cell.Value = c.Value Then
                found = True
                Exit For
            End If
        Next c
        
        ' If the value is not found in Sheet2, copy it to Sheet3
        If Not found Then
            cell.Copy ws3.Cells(ws3.Rows.Count, "A").End(xlUp).Offset(1)
        End If
    Next cell
End Sub
 
That works absolutely perfect. Superfast. Thank you very much for your time and effort!
 
Upvote 0

Excel Facts

Excel Joke
Why can't spreadsheets drive cars? They crash too often!

Forum statistics

Threads
1,223,889
Messages
6,175,223
Members
452,620
Latest member
dsubash

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top