VBA:将变量设置为“空".或“缺少"?处理多个可选参数? [英] VBA: Set variable to "Empty" or "Missing"? Handling multiple optional arguments?

查看:288
本文介绍了VBA:将变量设置为“空".或“缺少"?处理多个可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可能或希望将对象/数据设置为空"或缺少"变体? 我希望能够有条件地将可选参数传递给函数.有时我想使用可选参数,有时则不需要.

Is it possible, or desirable, to set objects/data to an "Empty" or "Missing" variant? I want to be able to conditionally pass optional arguments to a function. Sometimes I want to use an optional argument, sometimes I don't.

在Python中,通过使用** kwdargs将字典或列表解压缩到函数参数中,您可以轻松地传递所需的任何可选参数.是否有类似的东西(或在VBA中破解它的方法),以便您可以传入Empty/Missing可选参数?

In Python, you could easily pass through whichever optional arguments you wanted by using **kwdargs to unpack a dictionary or list into your function arguments. Is there something similar (or a way to hack it in VBA) so you can pass in Empty/Missing optional arguments?

尤其是,我尝试将 Application.Run 与任意数量的参数一起使用.

In particular, I'm trying to use Application.Run with an arbitrary number of arguments.

编辑:

我基本上是想这样做:

Public Function bob(Optional arg1 = 0, Optional arg2 = 0, Optional arg3 = 0, Optional arg4 = 0)
    bob = arg1 + arg2 + arg3 + arg4
End Function

Public Function joe(Optional arg1)
    joe = arg1 * 4
End Function


Public Sub RunArbitraryFunctions()
    'Run a giant list of arbitrary functions pseudocode

    Dim flist(1 To 500)
    flist(1) = "bob"
    flist(2) = "joe"
    flist(3) = "more arbitrary functions of arbitrary names"
    flist(N) = ".... and so on"

    Dim arglist1(1 To 4)        'arguments for bob
    Dim arglist2(1 To 1)        'arguments for joe 
    Dim arglist3(1 To M number of arguments for each ith function)


    For i = 1 To N
        'Execute Application.Run,
        'making sure the right number of arguments are passed in somehow.
        'It'd also be nice if there was a way to automatically unpack arglisti
        Application.Run flist(i) arglisti(1), arglisti(2), arglisti(3), ....
    Next i

End Sub

由于每个函数调用的参数数量都发生了变化,因此可以采用什么方法来确保将正确数量的输入输入到Application.Run中?

Because the number of arguments changes for each function call, what is the acceptable way to make sure the right number of inputs are input into Application.Run?

等效的Python代码为

The equivalent Python code would be

funclist = ['bob', 'joe', 'etc']
arglists = [[1,2,3],[1,2],[1,2,3,4,5], etc]

for args, funcs in zip(arglists, funclist):
    func1 = eval(funcs)
    output = func1(*args)

推荐答案

有两种方法可以更改例程必须提供给它的参数的数量:

There are two ways in which a routine can change the number of arguments that has to be provided to it:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆