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 stringpublic 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
argsto be of aStringtype...) As String indicates that the function will be returning a
Stringdata 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
VariantIt's the same as declaring a variable without specifying its type.
Dim aVariablewith is equivalent to
Dim aVariable as Variantbecause
Variantis the default type.so the
as Variantalways 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").ValueandRange("A1")- both are the same because.Valueis the default property of aRangeobject.What happens now is the compiler evaluates what value goes into the
aVariableunder the hood and assigns that type to the variable.Let's say you have
Like I've said now both are of
StringtypeNot 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 Stringis equal to the firststring(right after public) in C#in C# you would use a
returnkeyword while in VBA you replace thereturnkeyword 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)