Udf加速

Udf acceleration

有一个 Udf 运行良好,但速度较慢。 我知道如何加速 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

我同意关于失去 Application.Volatile 的评论之一。但是,我将详细说明一些内容,而不是评论中的内容。

正如 @JvdV 所指出的,使用 Application.Volatile 将在 任何 发生变化时导致重新计算。这会大大减慢计算速度(和工作簿,因为打开的工作簿更多或更大)。

不过,我也能从你的Cells(..., ...).Value's that with how the UDF is currently programmed, it may not always accurately update without the Application.Volitile if one of the values in the hardcode-referenced cells'变化中看出。

一种替代方法是重新处理 UDF,以将其检查 Diapozon 的范围作为附加输入参数包括在内。通过将这些范围作为参数包含在实际的 UDF 中,它告诉 Excel UDF 取决于这些范围,并且只要其中一个范围发生变化就应该重新计算。

例如在下面的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