简体   繁体   中英

Working with columns in a range in Excel VBA

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM