i'm trying to compare 2 worksheets and i have the below code that is working for me but it's kind of slow and also i can't get a dialog box to allow user to select the compare sources from both sheets and also i can't get it to select a column where to output the result. All is done in code but need it to be more flexible in excel front of house rather then editing all the times the code where to find the source of data. First sub will compare sheet1 against sheet2 and write the result in sheet 1 at the end of the table. Second sub will do the oppose compare sheet2 against sheet1 and write the result in sheet2 at the end of the table. Any help or guidance on how to achieve the above will be much appreciated.
Sub sample1()
Dim i, lastRow, currentRow As Long
Dim foundMatch As Range
Dim srcCriteria As String
Dim wsDest As Worksheet
Dim wsSrc As Worksheet
Set wsDest = ActiveWorkbook.Sheets("Sheet1")
Set wsSrc = ActiveWorkbook.Sheets("Sheet2")
lastRow = wsDest.Range("J" & Rows.Count).End(xlUp).Row
For i = 2 To lastRow
srcCriteria = wsDest.Range("J" & i).value
With wsSrc
Set foundMatch = .Columns(3).Find(What:=srcCriteria, After:=.Cells(1, 3), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) 'finds a match
End With
If foundMatch Is Nothing Then
wsDest.Range("S" & i).value = "0"
Else
With wsSrc
currentRow = .Columns(3).Find(What:=srcCriteria, After:=.Cells(1, 3), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Row
End With
wsDest.Range("S" & i).value = wsSrc.Range("I" & currentRow).value
End If
Next i
End Sub
Sub sample2()
Dim i, lastRow, currentRow As Long
Dim foundMatch As Range
Dim srcCriteria As String
Dim wsDest As Worksheet
Dim wsSrc As Worksheet
Set wsDest = ActiveWorkbook.Sheets("Sheet1")
Set wsSrc = ActiveWorkbook.Sheets("Sheet2")
lastRow = wsSrc.Range("C" & Rows.Count).End(xlUp).Row
For i = 2 To lastRow
srcCriteria = wsSrc.Range("C" & i).value
With wsDest
Set foundMatch = .Columns(10).Find(What:=srcCriteria, After:=.Cells(1, 10), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) 'finds a match
End With
If foundMatch Is Nothing Then
wsSrc.Range("M" & i).value = "To remove"
Else
With wsDest
currentRow = .Columns(10).Find(What:=srcCriteria, After:=.Cells(1, 10), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Row
End With
wsSrc.Range("M" & i).value = wsDest.Range("L" & currentRow).value
End If
Next i
End Sub