Home » excel » How to test if some of the optional parameters of an excel-VBA procedure is supplied?

How to test if some of the optional parameters of an excel-VBA procedure is supplied?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am trying to write a VBA macro to AutoFilter a table using the users input. I need the user to indicate the columns to filter and also the Criteria for that field. Therefore I thought to define a Sub with multiple optional arguments(parameters) to take users preference. My problem is how to check if an optional argument is supplied?

I understand that I can write a test for each parameter and then write a conditional statement for each possible option. But that doesn’t seem a smart way and am wondering if any one can suggest a solution. I should say that in the beginning we don’t know what’s the number of argument we expect to receive from the user.

Thanks for your responses.

How to&Answers:

A possibility would be to specify an absurd default. Then compare with the default.

Sub xyz( Optional p1 As String = "default_impossible_value")
    If p1 = "default_impossible_value" Then
       MsgBox "there_is_no_value_for_param_1"
    End If
End Sub

Then extend it to any number of parameter you wish as an entry:

Sub xyz( Optional p1 As String = "default_impossible_value"_
        ,Optional p2 As String = "default_impossible_value"_
        ,Optional p3 As String = "default_impossible_value"_
...
)
    If p1 = "default_impossible_value" Then
       MsgBox "there_is_no_value_for_param_1"
    End If
    If p2 = "default_impossible_value" Then
       MsgBox "there_is_no_value_for_param_2"
    End If
    If p3 = "default_impossible_value" Then
       MsgBox "there_is_no_value_for_param_3"
    End If
....
End Sub

Answer:

If the type of the variable is variant a solution would be to use IsMissing:

 If IsMissing(arg) Then
     MsgBox "missing parameter"
 End If

Then if you expect string or number, just check the value:

 Function func (Optional s as String, Optional n as Integer)

 If s = "" Then
     MsgBox "s is missing"
 End If

 If n = 0 Then
     MsgBox "n is missing"
 End