加速简单的用户定义功能

时间:2015-09-02 02:44:37

标签: vba optimization user-defined-functions

在Excel VBA中写入的用户定义函数似乎比简单地在工作表单元格中编写的函数运行得慢得多。有没有办法更快地运行它们?作为一个例子,我有一个非常简单的用户定义函数:

Function myweekday(mydate As Double)
    myweekday = Weekday(mydate)
End Function

基本上它与内置=工作日()函数完全相同。但是,在50,000个单元格上运行此程序需要大约5秒钟来计算,而只需使用内置函数需要几分之一秒。

如何使这样的用户定义函数运行得更快?

1 个答案:

答案 0 :(得分:4)

您可以将值作为范围传递,并让它在数组中一次性返回所有值。我刚刚尝试了50,000行,它立即返回所有值。您需要使用 CTRL + SHIFT + ENTER 输入UDF。

Function myweekday(mydate As Range) As Variant

Dim vMydate As Variant
Dim vMyWeekDay As Variant
Dim i As Long

vMydate = mydate.Value2
ReDim vMyWeekDay(1 To UBound(vMydate), 1 To 1)

    For i = 1 To UBound(vMydate)
        vMyWeekDay(i, 1) = Weekday(vMydate(i, 1))
    Next i

myweekday = vMyWeekDay

End Function

enter image description here