1

I have a VBA function with multiple arguments, which I need to get from the excel sheet and not from a sub, how do I divide the inputs into the number of parameters i need for my function?

Ex:

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:

This is how I have been trying to get the values

2 Answers 2

4

if you want to handle multiple arguments of which you don't know the number of, then use ParamArray argument

for instance, assuming func() should simply sum the arguments you pass it:

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
Sign up to request clarification or add additional context in comments.

Comments

0

Is this what you want?

Code:

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

   TestFunction = a + b

End Function

Excel Sheet:

=TestFunction(A1,B1)

2 Comments

Yes, however when I choose the cells in excel, and divide the parameters with a comma, I still get an error. The cell where I want the function to be in says that the value is wrong. What I want to know is how can I manually enter three excel cell values as parameters to a vba function.
My understanding of the comma and simicolon difference is that some language settings use one, while others use the other. For the problem you are encountering, I would need to know which equations you are using, however, cells are sometimes formatted as text or some alternative format. The other thing that sometimes goes wrong is a divide by zero situation. Have you stepped through the calculations with the debugger?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.