Hi,
Try this code :
You input the column number to compare separated by comma : 1,2,3,...
use -1 to compare all
Sub CompareColumns()
Dim ar1, ar2, arCol
Dim Dic1
Dim i As Long, ii As Long, k As Long, n As Long
Dim col As String, temp As String
On Error GoTo errhandler
ar1 = Sheets(1).Cells(1).CurrentRegion
ar2 = Sheets(2).Cells(2).CurrentRegion
Set Dic1 = CreateObject("Scripting.Dictionary")
' / Get columns to compare
col = InputBox("Columns to compare separated by comma (-1 for all)" & vbLf & _
"(example : 1,2,4)", "Columns number to compare", "-1")
col = Replace(col, " ", "")
' / Build array of columns to compare
If col = "-1" Then '/ all columns
ReDim arCol(0 To UBound(ar1, 2) - 1)
For i = 0 To UBound(ar1, 2) - 1
arCol(i) = i + 1
Next i
Else
arCol = Split(col, ",")
End If
' / Create dictionary
For i = 2 To UBound(ar1, 1)
temp = ""
For k = 0 To UBound(arCol)
temp = temp & ar1(i, arCol(k)) & Chr(2)
Next k
If Not Dic1.exists(temp) Then Dic1.Add temp, i
Next i
' / With data in sheet2, look if exists in sheet1
n = 2
For i = 2 To UBound(ar2, 1)
temp = ""
For k = 0 To UBound(arCol)
temp = temp & ar2(i, arCol(k)) & Chr(2)
Next k
If Dic1.exists(temp) Then 'if item exists, write back in array
For ii = 1 To UBound(ar2, 2)
ar1(n, ii) = ar2(i, ii)
Next ii
n = n + 1
End If
Next i
' / Write results in sheet 3
With Sheets(3).Cells(1)
.CurrentRegion.Clear
.Resize(n - 1, UBound(ar1, 2)) = ar1
End With
Exit Sub
errhandler:
MsgBox "Execution error. Check if valid column numbers provided. " & vbLf & col
End Sub
Bookmarks