The Problem
For beginning programmers, functions and subroutines seem to be different names for essentially the same thing, a bunch of code that does something that needs to get done
Sub and Function observable similarity
Here is a list of what makes Subs and Functions seem like the same thing
- The first line is Sub or "Function", the name for the code, and (optionally) some parameters
- The new programmer is taught to declare data at the beginning
- The same building blocks for the internal code are the same: If Then Else, Do and For loops, This = That, etc.
- Subs' and Functions' code can include Function calls as well as execute Subs
Subs and Functions observable dissimilarity
There are some differences that give a clue as to why there are two different things.
- A Function can be declared with an "As ..." phrase. A Sub cannot.
- When recording a Macro through Excel, the result is a Sub. It is always a Sub, it is never a Function.
- Once written, a Function can be used in a worksheet but a Sub cannot.
Subs and Functions: Different Purposes
This may sounds like I'm stating the obvious after the above, but the difference between a Sub and a Function from a "What's the main purpose of the code?" perspective is whether, from the calling module's perspective, is to provide something ( Function) or accomplish something (Sub).
Metaphorically, consider a hot summer day when a cold drink would be tasty. Do you want someone to bring you iced tea or make iced tea for you? The former is more like a Function, the latter like a Sub.
Metaphorically, consider a hot summer day when a cold drink would be tasty. Do you want someone to bring you iced tea or make iced tea for you? The former is more like a Function, the latter like a Sub.
No comments:
Post a Comment