What is a Sub
When you speak of functions and subs, the only difference is that a function
can return a value. If you write a function and don't return a value, even
though you might declare it as function, it could just as well be declared as
sub.
There is no difference in what can be contained in the function.
that is all true when you are going to only call these procedures from VBA.
You can make a special type of Function called a User Defined Function. this
Function can be used in the worksheet like a built in function. In this
case, when used this way, it has certain restrictions on what type of actions
it can perform. In terms of affecting the excel environment, except for a
few anomalies, it can only return a value to the cell in which the function
is placed - just like built-in functions.
for both subs and functions that don't return values (or the retuned value
is not used), the arguments are not placed in parentheses unless you preface
it with the call function
Sub myMacro(arg1, arg2)
is called with
MyMacro arg1, arg2
or
Cal MyMacro(arg1, arg2)
likewise if I had a function
Sub Myfunction(arg1, arg2)
myFunction = arg1 * arg2
cells(1,2) = arg1*arg2
End Function
could be used
MyFunction arg1, arg2 ' no value returned
Call MyFunction(arg1, arg2) ' no value retuned
res = MyFunction(arg1, arg2) ' value returned.
This can not be uses as a UDF in the worksheet because it sets a value in a
cell. If I commented out that line, it could be used in a cell.
--
Regards,
Tom Ogilvy
"Abode" wrote:
Im very new to Excel and I've found the ability to program functions very
useful and a good way to give me a break from working while still working. I
see many people here asking questions and getting answers with code that
seems to be a 'sub'. I'd love to start learning how to program them but I
dont know how to implement them into Excel and why they are more useful than
functions (other than the ability to obviously be far more complex) Oddly
enough I didn't quite see this question being asked anywhere. Thank you for
your time
Mark
|