I am quite new to writing functions in excel (been mainly coding sub procedures).
I was wondering what the following function declaration means?
public function function_name(args as string) as string
I understand everything up to the second instance of as string
. This is something new to me and I am not sure how this is different to just declaring:
public function function_name(args as string)
public function function_name(args as string) as string
public is the access definition. public means accessible across the VBA Project
function means that is it a function (meaning it is supposed to return something)
function_name is the name of a function (can't start with 1 or underscore)
args is the local parameter name to be used within the body of function
args as String indicates that the function is expecting the
args
to be of aString
type...) As String indicates that the function will be returning a
String
data type. So if you have had dimensioned a String type variable you would be able to assign a value to it using the function.the standard (default) declaration without explicitly specifying the type to be returned returns a
Variant
It's the same as declaring a variable without specifying its type.
Dim aVariable
with is equivalent to
Dim aVariable as Variant
because
Variant
is the default type.so the
as Variant
always exist unless there is a different type specified. And because it's default you do not have to explicitly code it.It's somehow similar to
Range("A1").Value
andRange("A1")
- both are the same because.Value
is the default property of aRange
object.What happens now is the compiler evaluates what value goes into the
aVariable
under the hood and assigns that type to the variable.Let's say you have
Like I've said now both are of
String
typeNot sure how familiar with for example C# you are but in C# you declare the return type of a function right after the access modifier ie.
so in VB/VBA the second
as String
is equal to the firststring
(right after public) in C#in C# you would use a
return
keyword while in VBA you replace thereturn
keyword with the function name. Therefore in VBA a very basic sampleFunction returns first 3 characters of the string you have passed to it (if the string is longer then 3 characters, if not it returns the string you passed to the function)