我创建了一个接受数组输入的 Excel UDF。我希望它只允许数组中包含偶数个项目。这是代码:(它很短,所以我将全部发布,这样您就可以了解一些上下文)
Function SUBSTITUTEMULTI(inputString As String, ParamArray criteria() As Variant) as String
Dim subWhat As String
Dim forWhat As String
Dim x As Single
If UBound(criteria()) Mod 2 = 0 Then
'check whether an even number of arguments is input
MsgBox "You've entered too few arguments for this function", vbExclamation
Else
x = 0
For Each element In criteria
If x = 0 Then
subWhat = element
Else
forWhat = element
inputString = WorksheetFunction.Substitute(inputString, subWhat, forWhat)
End If
x = 1 - x
Next element
SUBSTITUTEMULTI = inputString
End If
End Function
目前,我返回一个消息框,看起来像 Excel 自己的消息框,当您输入 SUBSTITUTE()
且缺少第三个参数时,会出现该消息框。但是,当您使用 SUBSTITUTE()
或任何类似函数执行此操作时,Excel 会阻止您输入公式,而是让您重新输入公式,以便您可以修复有问题的函数。
我希望这样,否则我的函数可以以其损坏状态(奇数个参数)粘贴到多个单元格中,这意味着重新计算时消息框会出现多次!
如何修复代码,以便在检测到不正确的参数(数组中的项目数为奇数)时,用户会自动返回到编辑公式步骤?
最佳答案
当输入的参数数量不正确时,让函数返回错误。
返回值必须是 Variant 而不是 String。
用 SUBSTITUTEMULTI=CVErr(xlErrValue)
替换您的消息框。
错误列表:
xlErrDiv0
表示#DIV/0
错误xlErrNA
表示#N/A
错误xlErrName
表示#NAME?
错误xlErrNull
表示#NULL
错误xlErrNum
表示#NUM
错误xlErrRef
表示#REF
错误xlErrValue
表示#VALUE
错误
( http://www.cpearson.com/excel/writingfunctionsinvba.aspx )
关于vba - 如何在 Excel UDF 中强制使用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42347011/