如何在Excel UDF中强制参数

Gre*_*edo 6 excel vba excel-vba excel-udf

我创建了一个接受数组输入的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
Run Code Online (Sandbox Code Playgroud)

目前,我返回一个消息框,看起来像Excel自己的消息框,当您输入SUBSTITUTE()时缺少第三个参数.但是,当您使用SUBSTITUTE()或执行任何类似的功能时,Excel会阻止您输入公式,而是单击您重新输入它,以便您可以修复故障功能.我想这样,否则我的函数可以在其破碎状态(奇数个参数)中粘贴到几个单元格中,这意味着重新计算时消息框会出现几次!

如何修复代码,以便在检测到错误的参数(数组中奇数个项目)时,用户是否会自动返回到编辑公式步骤?

Cal*_*mDA 2

这不是一个特别好的解决方案。SendKeys一般来说,不鼓励使用,并且此解决方案仅在您禁用了您的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
Run Code Online (Sandbox Code Playgroud)