簡體   English   中英

在Excel VBA中使用范圍內的列

[英]Working with columns in a range in Excel VBA

我有一個比較兩列並返回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是有實驗但沒有差別來糾正執行。

您必須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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM