如何在Excel UDF中强制参数

我创build了一个接受数组input的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自己的一个,当你inputSUBSTITUTE()时出现第三个参数丢失。 但是,当您使用SUBSTITUTE()或任何类似的函数执行此操作时,Excel会阻止您input公式,而是将其单击回来,以便修复错误的function。 我想这样做,否则我的函数可以粘贴到它的断开状态(奇数个参数)到几个单元格中,这意味着消息框在重新计算时会出现几次!

如何修复代码,以便如果检测到不正确的参数(数组中有奇数个项目),那么用户将自动返回到编辑公式步骤?

这不是一个特别好的解决scheme。 一般来说,使用SendKeys是不鼓励的,这个解决scheme只有在你禁用了MoveAfterReturn属性的情况下才起作用(即在下面的图中没有选中)

在这里输入图像说明

 Function test(rng As Range) 'check condition If rng.Count <> 2 Then MsgBox "Incorrect..." SendKeys "{F2}", True Exit Function End If 'code here to be run if parameters are valid test = "Success" End Function 

当input的参数个数不正确时,函数返回一个错误。

返回将不得不是一个Variant而不是String。

使用SUBSTITUTEMULTI=CVErr(xlErrValue)replace您的msgbox。

错误列表:

  • xlErrDiv0xlErrDiv0 #DIV/0错误
  • xlErrNA #N/A错误
  • xlErrName#NAME? 错误
  • xlErrNull错误
  • xlErrNum #NUM错误
  • xlErrRef#REF错误
  • xlErrValue发生#VALUE错误

http://www.cpearson.com/excel/writingfunctionsinvba.aspx