0

I have a function that compares two columns and returns true or false. I have another function that takes a range as an input, and should do all pairwise comparisons of the columns in that range.

However I seem to be drawing a blank at extracting (and storing) columns from a range. The function exits when I ask for the ith column. This is my code:

Function CompareAllColumns(r As Range, o As Range)
Dim numCols As Integer
Dim i As Integer
Dim j As Integer
Dim col1 As Range
Dim col2 As Range
Dim Matches As Integer

Matches = 0
numCols = r.Columns.Count
Dim ac1 As String
Dim ac2 As String
Dim a As String

a = r.Address

For i = 1 To numCols - 1
    col1 = r.Columns(i).Select
    ac1 = col1.Address

    For j = i + 1 To numCols
        col2 = r.Columns(j).Select

        If (Compare(col1, col2)) Then
            o.Value = "Columns " & i & " and " & j & " are the same"
            o = o.Offset(1).Select
            Matches = Matches + 1
        End If
    Next
Next

CompareAllColumns = Matches
End Function

It exits on the line col1 = r.Columns(1).Select - the Select is there experimentally but makes no difference to correct execution.

1
  • You have to use Set with objects, so Set col1 = r.Columns(i). Commented Jul 27, 2017 at 0:04

1 Answer 1

3

You have to Set objects, you can't use the default Let with them.

Also, as this appears to be a UDF (based on your comment "It exits on the line col1 = r.Columns(1).Select", rather than you saying that it crashes out on that line), you need to be aware that your code won't be permitted to make changes to Excel cells other than by returning a value from the function.

Function CompareAllColumns(r As Range, o As Range)
    Dim numCols As Integer
    Dim i As Integer
    Dim j As Integer
    Dim col1 As Range
    Dim col2 As Range
    Dim Matches As Integer

    Matches = 0
    numCols = r.Columns.Count
    Dim ac1 As String
    Dim ac2 As String
    Dim a As String

    a = r.Address

    For i = 1 To numCols - 1
        'use Set for an object
        Set col1 = r.Columns(i)
        ac1 = col1.Address

        For j = i + 1 To numCols
            'use Set for an object
            Set col2 = r.Columns(j)

            If Compare(col1, col2) Then
                'You can't set values within a UDF
                'o.Value = "Columns " & i & " and " & j & " are the same"
                'You can't "Select" things within a UDF
                'o = o.Offset(1).Select
                Matches = Matches + 1
            End If
        Next
    Next

    CompareAllColumns = Matches
End Function
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.