Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在VBA中将数组解包为ParamArray_Vba_Paramarray - Fatal编程技术网

在VBA中将数组解包为ParamArray

在VBA中将数组解包为ParamArray,vba,paramarray,Vba,Paramarray,给定大小未知的数组和接受参数数组的过程,如何在不修改过程的情况下将数组作为参数数组传递 Sub Example(sequence() As String) UnModifiableSub sequence End Sub Sub UnModifiableSub(ParamArray bar()) ' bar(0) = sequence not bar = sequence End Sub 我看到的行为类似于Python的解包 def foo(*args): # identi

给定大小未知的数组和接受参数数组的过程,如何在不修改过程的情况下将数组作为参数数组传递

Sub Example(sequence() As String)
    UnModifiableSub sequence
End Sub

Sub UnModifiableSub(ParamArray bar())
    ' bar(0) = sequence not bar = sequence
End Sub
我看到的行为类似于Python的解包

def foo(*args):  # identical to ParamArray
    print(args)

x = [1,2,3,4]
foo(*x)  # what VBA can't do

我知道没有像Python中那样的内置解决方案,但是除了长的switch语句之外,任何残忍的实现都是可以接受的。

我不认为可以将参数传递为
ParamArray
,从本质上讲,您没有将参数分配给
ParamArray
本身,但是映射到
ParamArray
的元素

调用者传递的每个参数都映射到ParamArray变量中的一个元素。因此,ParamArray变量的元素数将与调用语句传递的参数数相同


对我来说,这个巨大的开关语句听起来有点残酷,但如果你必须调用的例程真的是无法修改的,那么这就是你所要做的。在VBA中,这是一个
Select Case
语句。不要忘记VBA数组可以有任意的索引,所以您必须同时测试
LBound
UBound
,除非您确定序列参数的来源

如果你可以编写自己的例程,那么有一种方法可以让你大部分时间都做自己想做的事情。您可以将数组分配给
Variant
类型的变量,如下所示:

Sub tryThis(v)
    Debug.Assert IsArray(v)
    Debug.Print v(LBound(v))
End Sub

Sub Example(sequence() As String)
    tryThis sequence
End Sub

Sub test()
    Dim s() As String

    ReDim s(1 To 2)
    s(1) = "a"
    s(2) = "b"

    Call Example(s)
End Sub
tryThis()
将取代您的
不可修改的子项。如果在即时窗口中运行
test()
,则会得到以下输出:

call test
a
我想这就是你想要的行为。(无论如何,这有点像。没有人想要任意数组索引。)当然,与Python相比,这是有限的。值得注意的是,如果要调用
tryThis()
,必须自己将“参数”放入数组中。本答案和家长问题中讨论了与此相关的一些权衡:

还有一些其他问题。例如,您不能只将
ParamArray
的内容传递给
tryThis()

您必须显式地传输到变量:

Sub gotchaFixed(ParamArray pa())
    Dim v
    v = pa

    Call tryThis(v)
End Sub

Sub test2()
    Call gotchaFixed("a", "b")
End Sub


UnModifiableSub-Array(sequence)
能起到作用吗?不,这会进一步嵌套它。然后
bar(0)(0)=序列
Sub gotchaFixed(ParamArray pa())
    Dim v
    v = pa

    Call tryThis(v)
End Sub

Sub test2()
    Call gotchaFixed("a", "b")
End Sub
call test2
a