• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 768
  • Last Modified:

VBA / Excel/ using optional Parameters

what is wrong with this piece of code, used in VB - Excel application

Function TestOptions(i As Integer, Optional k As Integer) As Integer

  If IsMissing(k) Then
             TestOptions = i
           Else
              TestOptions = i * k
           End If
End Function


Function TestOptionsStr(i As String, Optional k As String) As String

  If IsMissing(k) Then
             TestOptions = "one arg"
           Else
              TestOptions = "Two args"
           End If
End Function
0
BdLm
Asked:
BdLm
  • 3
1 Solution
 
mladenoviczCommented:
IsMissing works only for variant parameters.
try this
Function TestOptions(i As Integer, Optional k) As Integer

or with default value

Function TestOptions(i As Integer, Optional k As Integer=0) As Integer

  If k=0 Then
             TestOptions = i
           Else
              TestOptions = i * k
           End If
End Function
0
 
mladenoviczCommented:
MSDN:

Use the IsMissing function to detect whether or not optional Variant arguments have been provided in calling a procedure. IsMissing returns True if no value has been passed for the specified argument; otherwise, it returns False. If IsMissing returns True for an argument, use of the missing argument in other code may cause a user-defined error. If IsMissing is used on a ParamArray argument, it always returns False. To detect an empty ParamArray, test to see if thearray’s upper bound is less than its lower bound.

Note   IsMissing does not work on simple data types (such as Integer or Double) because, unlike Variants, they don't have a provision for a "missing" flag bit. Because of this, the syntax for typed optional arguments allows you to specify a default value. If the argument is omitted when the procedure is called, then the argument will have this default value, as in the example below:
0
 
mladenoviczCommented:
Here is the example that should be in my prev post

Sub MySub(Optional MyVar As String = "specialvalue")
    If MyVar = "specialvalue" Then
       ' MyVar was omitted.
    Else
    ...
End Sub
0
 
BdLmAuthor Commented:
thanks for the help, now my pgm is running .-)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now