requiring parameters to be of a certain type

J

Jamie Martin

Can I force a Function to take only a String or other data type as an
argument? In Java one had to do this . . . I'm worried if I don't specify, I
might get weird errors if I accidentally pass the wrong type of information
to a Function or called Sub procedure.
 
B

Bob Kilmer

Just declare the argument type in the function declaration.

Function foo(f as String) As String
Function moo(m as Long) As Integer
Function noo(n as Single, m as Double) As Collection
Function poo(p as Variant) As Workbook

If you leave off the type, the type defaults to Variant, which will accept
anything, although at a some cost of overhead and type checking.

You should understand that VB coerces numerics types to strings and strings
that appear numeric to numeric types according to the context (argument type
or operator). In other words foo(5) would work as well as foo("5") as far as
VB is concerned. If you do or do not want numeric types, you can use
IsNumeric to differentiate. You can also check variant arguments for their
subtype (VarType).

See help regarding the keywords/functions/operators Is, IsNumeric(),
IsObject(), TypeName, TypeOf, VarType.
 
J

Jamie Martin

Awesome. Why do I need to say "As String" twice?

Bob Kilmer said:
Just declare the argument type in the function declaration.

Function foo(f as String) As String
Function moo(m as Long) As Integer
Function noo(n as Single, m as Double) As Collection
Function poo(p as Variant) As Workbook

If you leave off the type, the type defaults to Variant, which will accept
anything, although at a some cost of overhead and type checking.

You should understand that VB coerces numerics types to strings and strings
that appear numeric to numeric types according to the context (argument type
or operator). In other words foo(5) would work as well as foo("5") as far as
VB is concerned. If you do or do not want numeric types, you can use
IsNumeric to differentiate. You can also check variant arguments for their
subtype (VarType).

See help regarding the keywords/functions/operators Is, IsNumeric(),
IsObject(), TypeName, TypeOf, VarType.

--
Bob Kilmer


specify,
 
J

J.E. McGimpsey

The first declares the argument (f) data type, the next declares the
data type returned by the Function (default is Variant)
 
B

Bob Kilmer

In the case of a Sub (which does not itself return a value) the second As
<type> is not used and would be a syntax error.

(Subs can modify arguments passed ByRef (the default) and result in a
modified argument value for the caller but they are not allowed to return
values that can be assigned like a function.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top