Home » excel » excel – How to get 2 non-adjacent columns to work with?

excel – How to get 2 non-adjacent columns to work with?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to build a macro that compares two columns to see whether or not they are the same. This is the function.

Sub Compare()
Dim LastRow As Integer
LastRow = Worksheets("Sheet1").Range("A1048576").End(xlUp).Row 
For i=2 to LastRow
    If Range("A" & i).Value = Range("B" & i).Value Then
        Range("C" & i).Value = True
    Else
        Range("C" & i).Value = False
    End If
End Sub

Right now it is hard coded to compare column A and B then output True/False into column C. What I want to do is have the user select ONLY 2 columns from their excel sheet and then run this macro which then compares the two selected columns by the user. These 2 columns can be non-adjacent to each other, so for example the user can select column A and column K to compare the values between them.

How to&Answers:

You need to check the .Areas property of non adjacent columns.

Sub CompareTwo()
    dim rng as range, i as long
    set rng = intersect(selection, selection.parent.usedrange)

    if rng.areas.count>1 then
        for i=1 to rng.areas(1).rows.count
            rng.areas(2).cells(i).offset(0, 1) = cbool(rng.areas(1).cells(i).value = rng.areas(2).cells(i).value)
        next i
    else
        for i=1 to rng.rows.count
            rng.cells(i).offset(0, 2) = cbool(rng.cells(i).value = rng.cells(i).value)
        next i
    end if
End Sub

To put the results in a new column at the end of the excel sheet, use Find with xlPrevious and xlByColumns to locate the last used column then offset 1.