具有多个参数的功能

时间:2016-11-05 17:56:17

标签: excel vba function arguments

我有一个带有多个参数的VBA函数,我需要从excel表而不是从sub获取,如何将输入分成我的函数所需的参数数量?

例如:

Function func(a as double,b as double) as double
    'calculations
    'some return value
End Function

这就是我尝试获取值的方式:

This is how I have been trying to get the values

2 个答案:

答案 0 :(得分:2)

如果你想处理你不知道其数量的多个参数,那么使用ParamArray参数

例如,假设func()应该简单地对你传递的参数求和:

Function func(ParamArray args() As Variant) As Double
    Dim i As Long
    Dim cell As Range

    For i = LBound(args) To UBound(args) '<--| loop through each passed argument
        If TypeName(args(i)) = "Range" Then '<--| if the current element is a Range
            For Each cell In args(i) '<--| loop through range cells
                func = func + cell.Value
            Next cell
        Else '<--| otherwise
            func = func + args(i) '<--| simply process the current argument value
        End If
    Next i
End Function

答案 1 :(得分:0)

这是你想要的吗?

代码:

Function TestFunction(a As Double, b As Double) As Double

   TestFunction = a + b

End Function

Excel表格:

=TestFunction(A1,B1)