两种使用方式之间的主要区别在于WorksheetFunction
提出一个致命错误,停在相应的黄色代码线上并且Application
does not,在同样的情况下,如果出现任何错误。
的情况下WorksheetFunction
,您只能使用来处理错误On Error Resume Next
,这限制了使用函数 return 的可能性,而且它也不是那么优雅。
在某些(罕见)情况下,两种方式都会返回相同的函数是不同的。我的以下答案不会提及这些特性,它将显示两种情况下引发错误的示例,但主要集中于使用所创建的优势和可能性Application
代替WorksheetFunction
:
如果您使用:Debug.Print WorksheetFunction.VLookup("code",A2:F1000,3, False)
它将提供智能感知建议,但会引发运行时错误('1004'):'无法获取 WorksheetFunction 类的 VLookup 属性',如果没有任何匹配Lookup_value
in Table_array
.
Using
Debug.Print Application.VLookup("code",A2:F1000,3, False) 'does not raise a run-time error
'it will return Error 2042
乍一看,这似乎没什么大不了的,但它为使用不同的行为方式提供了很多可能性。
让我们研究一个非常通用的函数:Match
我不会使用WorksheetFunction
如果不匹配,它总是会引发运行时错误。我只会关注Application.Match
优点:
Sub testApplicationMatchAdvantages()
Dim ret, arr
arr = Array(1, 3, 6, 9, 11)
arr = Split("1, 3, 6, 9, 11", ", ")
ret = Application.match("5", arr, 0)
If IsError(ret) Then Debug.Print "5" & " does not exist in the array...": 'Exit Sub
ret = Application.match("9", arr, 0)
If IsNumeric(ret) Then
Debug.Print 9 & " is the " & ret & "th element of the array and it will be removed:"
arr = filter(arr, arr(ret - 1), False) 'arr(ret)-1 because arr is zero based
Debug.Print Join(arr, "|") '9 has been removed
Else
Debug.Print 9 & " does not exist in the array...": Exit Sub
End If
Dim arr2, arr3
arr2 = Array(1, 3, 4, 9)
arr2 = Split("1, 4, 3, 9", ", ")
arr3 = Application.IfError(Application.match(arr2, arr, 0), "X")
Debug.Print Join(arr3, "|") 'meaning that the first element in arr2 matches the first one in arr
'and the third one, matches the second of arr
'using:
arr3 = Application.match(arr2, arr, 0) 'it returns a 1 based array, but it cannot be returned by joinning
' because of Error 2042 elements
Dim i As Long
For i = 1 To UBound(arr3)
Debug.Print arr3(i);
Next i
End Sub
你还可以玩Application.Index
, Application.VLookup
它们还能够返回播放宽度的数组。
综上所述,Application
跳过运行时致命错误并提供许多使用返回的可能性。无论是否有错误,都是包含错误编号元素的数组。不能使用以下方法处理WorksheetFunction
...