Why Use Subs at All?
Almost every Sub could be a Function...but that doesn't mean it's a good idea.
This article is one in a series on Subs vs. Functions in VBA.
One of the "additional facts" from my Subs vs. Functions article was this:
(Almost) everySubcould be aFunction...but that doesn't mean it's a good idea
Which raises the obvious question, Why not?
(Almost) Every Sub Could be a Function
As a reminder, a Function returns a result while a Sub does not.
Of course, you don't need to do anything with the return value from a Function. You could simply ignore it. That's why (most) Subs could just as easily be Functions.
For example, you could change this Sub...
Sub HelloWorld()
Debug.Print "Hello, world."
End Sub...to this Function...
Function HelloWorld()
Debug.Print "Hello, world."
End Function...and all of your calling code will continue to work just fine. You won't get any compile errors. It won't create any runtime errors. Everything will work exactly the same.
If that's the case, why not "simplify" your life by abandoning Subs entirely?
It's All About Intent
The most important reason why a Sub is better than a Function is that it clarifies your intent as a programmer.
A Sub is your way of saying, "This procedure has nothing to return."
A Function where you do not set an explicit return value will make people wonder whether you've omitted the return value on purpose or not.
Reasons to Use Subs Rather Than Functions
From StackOverflow: Sub vs. Function without a return value
What is the sense of a subroutine (Sub)? Why not use aFunctionwithout a return value?
What I mean is, why does the keywordSubexist? I can useFunctionwithout declaring a return value and have the same, no?
The entire Q&A is worth reading. I'll recap the reasons from several of the answers in list form below. Follow the link above for full explanations.
- Because using a
Subclarifies your intent. - Because a non-returning function makes no sense.
- Because static code analysis tools will complain about a
Functionwith no return value. - Because using a
Subclarifies your intent. - A
Subprevents the caller from trying to assign a non-existent return value to something. - A
Subis more efficient because aFunctionhas to push its return value onto the stack. - BECAUSE USING A
SubCLARIFIES YOUR INTENT.
Cover image created with Microsoft Designer