Link to home
Start Free TrialLog in
Avatar of ResourcefulDB
ResourcefulDB

asked on

Excel Vba function, optional argument, or string comparison

Hi expert,

Here is one simple VBA function with optional argument, please help to see what is best to make it work.

Function arith(x, y, Optional operation As String)
    If operation = addition Then
            arith = x + y
        ElseIf operation = subtract Then
            arith = x - y
        ElseIf operation = multiply Then
            arith = x * y
        Else
            arith = x + y      
    End If        
End Function


The function use addition as default operation.

If we set operation = "subtract", then in the input we use =arith(3, 5, "subtract"), it does work. However, we will like to just use =arith(3, 5, substract), what is the best way to make it work.

Thanks,
RDB
ASKER CERTIFIED SOLUTION
Avatar of [ fanpages ]
[ fanpages ]

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The solution above will work fine if you are calling arith from other code. But if, as it seems, you are trying to achieve this so that it works for functions input into cells of a workbook, then you're asking for a lot. I am not sure why you need to do this without the quotes, but one suggestion I have is to consider adding another function like this:

Public Function addition()
    addition = "addition"
End Function

Open in new window


You can then call your original arith function with the following:
=arith(7,6,addition())

Open in new window


Without knowing the underlying reason for your request it is difficult to know whether this could be of any help.
How about setting your Operation function in a separate cell and then referring to that cell rather than typing it in.

I believe you would set the Operation as a range rather than a string:

Function arith(x, y, Optional operation As Range)

Thanks
Rob H
Avatar of ResourcefulDB
ResourcefulDB

ASKER

I tried out codes by fanpages, it gives an error message "variable not defined" and the cursor points to the code "eNum_Operation = addition".

what could be the problem.
Can you post the code that fails, & details about which version of MS-Excel you are using, please?

A sample workbook (with any sensitive information removed) would be ideal.
ok, I started Excel fresh and input only your code and it works. It is Excel 2010.