代码之家  ›  专栏  ›  技术社区  ›  barciewicz

为什么这个查找函数很慢?

  •  1
  • barciewicz  · 技术社区  · 6 年前

    如果在指定范围内找到单元格值,我编写了以下UDF函数以返回true,否则返回false:

    Function find_in_range(value_to_find As Variant, lookup_range As Range) As Boolean
    
    For Each cell In lookup_range.Cells.SpecialCells(xlConstants)
        If cell.Value = value_to_find Then
            find_in_range = True
            Exit For
        Else
            find_in_range = False
        End If
    Next cell
    
    End Function
    

    但是,它比vlookup慢得多。

    为什么会这样?有没有办法让它更快?使用什么魔法使vlookup搜索更快?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Vityata    6 年前

    这是提高速度的一种方法:

    Public Function findInRange(valueToFind As Variant, lookupRange As Range) As Boolean
        findInRange = Not IsError(Application.Match(valueToFind, lookupRange, 0))
    End Function
    

    使用什么魔法使vlookup搜索更快?

    • 用C语言编程
        2
  •  1
  •   Samuel Hulla    6 年前

    除非你绝对坚持用聚乙烯填充 (非字面意义上) ,Excel已具有内置函数 Find 返回 Range 如果找到,或 Nothing 如果没有

    您可以进一步将其修改为一个函数,该函数的计算结果为 Boolean

    Option Explicit
    Function isFound(ByVal value_to_find As String, ByVal in_range as Range) As Boolean
    
     If in_range.Find(value_to_find, lookin:= xlValues) Is Nothing Then
        isFound = False
     Else
        isFound = True
     End If
    
    End Function
    

    退换商品 true 如果在范围内可以找到值,则返回 false


    一般来说,如果你能做点什么 如果没有循环,通常意味着它更快

        3
  •  1
  •   Pᴇʜ    6 年前

    在大多数情况下(我甚至会说全部),内置函数都比VBA快。它们已经被编译并且是本机代码。

    它们也可以在VBA不能使用的情况下使用多线程。所有这些效果都使它们的动作更快。你也不想重新发明轮子。所以我建议尽可能使用内置函数。

    推荐文章