Below is the code I have to compare the row values of the columns that have the same header ‘abc’, ‘def’, and ‘ghi’ in ws_checks, assuming those columns are in both Sheet1 and Sheet2. How can it be expanded to compare multiple columns (not just 2, can be any number of columns in 1 sheet or across all Sheets 1 to 5) that share the same column header?
”’
Dim r, lr, lr1, lr2, col1, col2, lc_checks, nextCol As Long
Dim Rng1, Rng2, Found1, Found2 As Range
Dim foundX As Boolean
Dim header, headerList As Variant
' List of column headers to compare
headerList = Array("abc", "def", "ghi")
' Loop through each header in the list
For Each header In headerList
' Find the column index of the header in both sheets
On Error Resume Next ' Handle the case where header might not be found
col1 = Application.Match(header, ws1.Rows(2), 0)
col2 = Application.Match(header, ws2.Rows(2), 0)
On Error GoTo 0
' Find the last row with data in the columns
lr1 = ws1.Cells(ws1.Rows.Count, col1).End(xlUp).Row
lr2 = ws2.Cells(ws2.Rows.Count, col2).End(xlUp).Row
' Find the next column to paste the next check
lc_checks = ws_checks.Cells(1, Columns.Count).End(xlToLeft).Column
nextCol = lc_checks + 1
' Compare values in the rows of the current column header
For r = 3 To Application.WorksheetFunction.Min(lr1, lr2)
ws_checks.Cells(1, nextCol).Value = ws1.Cells(2, col1).Value
If ws1.Cells(r, col1).Value = ws2.Cells(r, col2).Value Then
ws_checks.Cells(r - 1, nextCol).Value = "Match"
Else: ws_checks.Cells(r - 1, nextCol).Value = "Mismatch"
Next r
”’