从函数名称存储在数组中的过程调用参数化函数

时间:2014-10-13 13:17:44

标签: excel-vba vba excel

我有很多功能。考虑n = 10

我已将这n个函数的名称存储在名为Array1

的数组中

示例:Array1 = Array(" Function_1",Function_2"," Function_3" ............," Function_10&# 34)

这些功能的一般结构:

函数Function_1(TestRange as Range)作为范围

......一些代码

结束功能

当我使用数组索引调用此函数时,如何传递TestRange的参数?

例如:

Sub main()

Dim MainRange as Range

For i = 1 To UBound(Array1)
    Set MainRange = Application.Run(Array1(i))
Next

End Sub

当我尝试运行main()过程时遇到以下错误:

运行时错误' 449' :参数不可选

有人可以帮我吗?

谢谢,

Akshat

1 个答案:

答案 0 :(得分:0)

Sub Main()
    Dim arr, x
    Dim rngIn As Range, rngOut As Range

    arr = Array("Func1", "Func2")
    Set rngIn = ActiveSheet.Range("A1")

    For x = 0 To UBound(arr)
        Set rngOut = Application.Run(arr(x), rngIn)
        Debug.Print rngOut.Address()
    Next x

End Sub

Function Func1(rng As Range) As Range
    Set Func1 = rng.Resize(10, 1)
End Function

Function Func2(rng As Range) As Range
    Set Func2 = rng.Resize(1, 10)
End Function