requiring parameters to be of a certain type

  • Thread starter Thread starter Jamie Martin
  • Start date Start date
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.
 
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.
 
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,
 
The first declares the argument (f) data type, the next declares the
data type returned by the Function (default is Variant)
 
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.)
 
Back
Top