Why Use Subs at All?

Almost every Sub could be a Function...but that doesn't mean it's a good idea.

Why Use Subs at All?

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) every Sub could be a Function...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 a Function without a return value?

What I mean is, why does the keyword Sub exist? I can use Function without 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 Sub clarifies your intent.
  • Because a non-returning function makes no sense.
  • Because static code analysis tools will complain about a Function with no return value.
  • Because using a Sub clarifies your intent.
  • A Sub prevents the caller from trying to assign a non-existent return value to something.
  • A Sub is more efficient because a Function has to push its return value onto the stack.
  • BECAUSE USING  A Sub CLARIFIES YOUR INTENT.

Cover image created with Microsoft Designer

All original code samples by Mike Wolfe are licensed under CC BY 4.0