Excel vba自定义查找功能:手动使用时速度快,宏速度慢

时间:2017-07-04 11:31:41

标签: excel vba excel-vba

我必须编写自己的查找功能,但其性能会有很大差异,这取决于我是否在工作表本身(通过' =')或通过宏手动调用它。我的宏执行以下操作:

Function betterSearch(searchCell As Range, aCol As Range, bCol As Range)
        For Each cell In aCol
            If LCase(cell.Value) = LCase(searchCell.Value) Then
                    betterSearch = bCol.Cells(cell.row, 1)
                    Exit For
            End If
            betterSearch = "Not found"
        Next
End Function

因此,宏会打开resultsWorkbookdataWorkbook,然后在resultWorkbook的{​​{1}}中搜索A列中的四个值,并返回其他列中的相应数据dataWorkbook

dataWorkbook

它真的很慢 - 1个文件需要几分钟。但是当我手动打开该文件并输入公式并按Enter键时,它会立即计算。

这里有什么问题?这种行为来自哪里?

1 个答案:

答案 0 :(得分:2)

如果它试图搜索整个列A:A,I:I(1百万个单元格),它可能会很慢

尝试将您的betterSearch更新为:

Function betterSearch(searchCell As Range, aCol As Range, bCol As Range)
    Dim itm As String, col1 As Variant, col2 As Variant, r As Long

    With ActiveSheet
        col1 = .UsedRange.Columns(aCol.Column)
        col2 = .UsedRange.Columns(bCol.Column)
    End With

    betterSearch = "Not found"
    itm = LCase(searchCell.Value2)

    For r = 1 To UBound(col1)
        If Len(col1(r, 1)) > 0 Then
            If LCase(col1(r, 1)) = itm Then
                betterSearch = col2(r, 1)
                Exit Function
            End If
        End If
    Next
End Function