简体   繁体   English

Excel VBA Ctrl-Shift-Enter 数组 function 与编写长工作表相比非常慢

[英]Excel VBA Ctrl-Shift-Enter array function very slow compared to writing long worksheet function

I have written a function NA_2_X(Range, Variant) to accept an array, convert all #NA to a Variant, and return the new array:我写了一个 function NA_2_X(Range, Variant)来接受一个数组,将所有#NA转换为一个 Variant,然后返回新数组:

{=NA_2_X(A1:A3000, 0)}

This is giving much slower execution than writing a laborious worksheet function:这比编写费力的工作表 function 的执行速度要慢得多:

{=IF(ISNA(A1:A3000), 0, A1:A3000)}

300 calls to NA_2_X() takes about 10s, whereas the IF() statement is almost instant.NA_2_X()的 300 次调用大约需要 10 秒,而IF()语句几乎是即时的。 Ultimately I want to do something more complicated and can't use an if() statement.最终我想做一些更复杂的事情并且不能使用if()语句。

Function NA_2_X(ByVal rng As Range, ByVal X As Variant) As Variant
    Dim NoRows As Long, NoCols As Long
    Dim r As Long, c As Long
    Dim ret() As Variant

    NoRows = rng.Rows.Count
    NoCols = rng.Columns.Count

    ReDim ret(1 To NoRows, 1 To NoCols)

    For c = 1 To NoCols
        For r = 1 To NoRows
            If Application.IsNA(rng(r, c)) Then
                ret(r, c) = X
            Else
                ret(r, c) = rng(r, c)
            End If
        Next r
    Next c

    NA_2_X = ret
    Exit Function
End Function

The loop itself seems pretty quick, it is just the few lines in the heart of the loop that seem so slow.循环本身似乎很快,只是循环中心的几行看起来很慢。 If I remove the call to IsNA() it takes about half the time, but is still slow.如果我删除对IsNA()的调用,它需要大约一半的时间,但仍然很慢。

In addition to BigBen's suggestion, replacing "Application.IsNA(rng(r,c))" with "IsError(tmp(r,c))" has made the routine nice and fast.除了 BigBen 的建议之外,将“Application.IsNA(rng(r,c))”替换为“IsError(tmp(r,c))”使例程变得又快又好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM