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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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:
Thanks
Rob H
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
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.
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.
A sample workbook (with any sensitive information removed) would be ideal.
ASKER
ok, I started Excel fresh and input only your code and it works. It is Excel 2010.
Open in new window
You can then call your original arith function with the following:
Open in new window
Without knowing the underlying reason for your request it is difficult to know whether this could be of any help.