Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

calling sub/function with optional args

Status
Not open for further replies.

sweetleaf

Programmer
Jan 16, 2001
439
CA
Hi there!

I'd like to call a sub that has some optional and non-optional arguments.

I tried using "Named Parameters" as below:

THE CALLING SUB

Private Sub CommandButton1_Click()

Dim k As Object

Dim l As String
Dim s, b As String

s = "Mark"
b = "Brion"

Set k = CreateObject("Project1.Class1")

l = k.test_this(s, last_name:=b)

Debug.Print l

End Sub

THE FUNCTION WITH OPTIONAL ARGS:

Public Function test_this(first_name As String, Optional last_name As String)

test_this = first_name & " ^ " & last_name

End Function

I keep getting a type mismatched error..

Are "Named Arguments" the only way of calling sub/functions with optional args?

Thanks so much!
 
I've tried simply putting in commas as place holders for Optional args which I am not providing values for..

But what happens when the optional args are last on the list?

I tried this:

test_call var1, var2,,var3,,,,

...but then i get "COMPILE ERROR --Expected exression"

Can anyone please help
Thanks
 
Dim s, b As String

makes s a variant and b a string. Try

Dim s As String
Dim b As String

and see how it goes.
 
and by the way, I'm just a VBA hack, so I'm not sure if this applies to VB, but your optional parameters must be the last in the list.

ie, you can have Sub MySub( s as String, i as Integer, Optional x as Double )

but you cannot have Sub MySub( s as String, Optional x as Double, i as Integer )

but you can have multiple optional parameters, provided that they are all at the end of the parameter list.

Further, if your optional is a variant, you can use IsMissing() to see if it was passed. Other types report as predictable defaults, integers=0, strings are probably "". Rather than leaving commas for omitted optional parameters, try using "Empty".
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top