使用Excel VBA中的范围中的列

时间:2017-07-26 23:58:59

标签: excel-vba vba excel

我有一个比较两列的函数,返回true或false。 我有另一个函数,它将范围作为输入,并且应该对该范围内的列进行所有成对比较。

但是我似乎在从一个范围中提取(和存储)列时留下了空白。当我要求第i列时,该函数退出。这是我的代码:

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

它退出col1 = r.Columns(1).Select行 - Select是实验性的,但对正确执行没有任何影响。

1 个答案:

答案 0 :(得分:3)

您必须使用Set个对象,不能使用默认Let

此外,由于这似乎是一个UDF(基于您的评论“它退出行col1 = r.Columns(1).Select”,而不是你说它在该行崩溃),你需要知道你的除了从函数返回值之外,不允许代码对Excel单元格进行更改。

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