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

Udf加速

  •  0
  • maxim465  · 技术社区  · 8 年前

    我知道如何加速Sub:

    Application.ScreenUpdating = False
    
    Application.Calculation = xlCalculationManual
    
    Application.EnableEvents = False
    

    这个适合功能吗? 如果没有,如何加快Udf?

    Function Fav(Diapozon As Range) As Long
        Application.Volatile
    
        Dim n As Long
    
        For x = 1 To 4
            For y = 0 To 1
                If Diapozon.Value = Cells(31, 3).Value Then
                    n = 0
                    Exit For
                End If
    
                If Diapozon.Value = Cells(x + 29, y + 10).Value Or Diapozon.Offset(0, 1).Value = Cells(x + 29, y + 10).Value Then
                    n = 1
                End If
             Next y
         Next x
    
         Fav = n
    End Function
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Mistella    8 年前

    我同意关于失去 Application.Volatile . 不过,我将详细阐述一点,而不仅仅是一个评论。

    作为 @JvdV 指出,使用 应用。易挥发 将导致重新计算 变化。这可能会极大地减慢计算速度(当打开更多或更大的工作簿时)。

    不过,我也能从你的 Cells(..., ...).Value 因为UDF当前的编程方式,如果没有 Application.Volitile

    另一种方法是重新处理UDF,以包括它正在检查的范围 Diapozon 作为附加输入参数。通过将这些范围作为参数包含在实际的自定义项中,它告诉Excel自定义项依赖于这些范围,并且在其中一个范围发生更改时应重新计算。

    例如,在下面的UDF代码中, nextDiapozon 是 Diapozon.Offset(0, 1) , nonMatch 是 Range("C31") Cells(31, 3) ,和 rngCompare Range("J30:K33") 相当于你循环穿过的细胞:

    Function Fav(Diapozon As Range, nextDiapozon As Range, nonMatch As Range, rngCompare As Range,) As Long
        Dim n As Long 'Default start value = 0
        Dim cell_var as Variant
    
        If Diapozon.Value <> nonMatch.Value then
            For each cell_var in rngCompare
                If Diapozon.Value = cell_var.Value Or nextDiapozon.Value = cell_var.Value Then
                    n = 1
                End If
            Next cell_var
        End If
    
        Fav = n
    End Function
    
    推荐文章