使用Instr VBA Excel进行索引匹配组合的UDF

时间:2018-09-12 23:44:37

标签: vba excel-vba excel-formula

我为UDF编写了这段代码,但是当我在许多单元格中使用它时,要花很多时间才能计算出来。有没有更有效的方法?

Public Function AGSIndexMatch(result_column As Range, lookup As Range, _
                                           lookup_column As Range) As Variant
    Dim cel As Range
    Dim b As String
    Dim i As Variant
    i = 1
    For Each cel In lookup_column
        On Error GoTo error_handler:
        If Not IsEmpty(cel) Then
            If InStr(1, cel.Value, lookup) <> 0 Then
                AGSIndexMatch = AGSIndexMatch & Application _
                  .WorksheetFunction.Index(result_column, i, 1) & Chr(10)
            End If
        End If
        i = i + 1
    Next cel
    If Len(AGSIndexMatch) <> 0 Then
        AGSIndexMatch = Left(AGSIndexMatch, Len(AGSIndexMatch) - 1)
    End If
    Exit Function
error_handler:
    AGSIndexMatch = Err.Description
End Function

1 个答案:

答案 0 :(得分:0)

在执行循环之前将数据移动到Variant Array中将大大节省时间-多少取决于范围的大小。

Public Function AGSIndexMatch( _
  result_column As Range, _
  lookup As Range, _
  lookup_column As Range) As Variant

    Dim rsc As Variant, src As Variant, lup As Variant
    rsc = result_column.Value2
    src = lookup_column.Value2
    lup = lookup.Value2
    Dim i As Long
    Dim res As String

    On Error GoTo error_handler:
    For i = 1 To UBound(src, 1)
        If src(i, 1) = lup Then
            res = res & Chr(10) & rsc(i, 1)
        End If
    Next
    AGSIndexMatch = Mid$(res, 2)

Exit Function
error_handler:
    AGSIndexMatch = Err.Description
End Function

根据数据的性质,可能还有其他方法可以使性能更好

相关问题