30.04.2017 Views

4523756273

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5<br />

VBA Sub and Function Procedures<br />

In This Chapter<br />

▶ Understanding the difference between Sub procedures and Function procedures<br />

▶ Executing Sub procedures (many ways)<br />

▶ Executing Function procedures (two ways)<br />

Several times in preceding chapters, I mention Sub procedures and allude<br />

to the fact that Function procedures also play a role in VBA. In this chapter,<br />

I clear up confusion about these concepts.<br />

Subs versus Functions<br />

The VBA code that you write in the Visual Basic Editor is known as a procedure.<br />

The two most common types of procedures are Sub and Function.<br />

✓ A Sub procedure is a group of VBA statements that performs an action<br />

(or actions) with Excel.<br />

✓ A Function procedure is a group of VBA statements that performs a calculation<br />

and returns a single value.<br />

Most of the macros you write in VBA are Sub procedures. You can think of<br />

a Sub procedure as being like a command: Execute the Sub procedure and<br />

something happens. (Of course, exactly what happens depends on the Sub<br />

procedure’s VBA code.)<br />

A Function is also a procedure, but it’s quite different from a Sub. You’re<br />

already familiar with the concept of a function. Excel includes many worksheet<br />

functions that you use every day (well, at least every weekday).<br />

Examples include SUM, PMT, and VLOOKUP. You use these worksheet functions<br />

in formulas. Each function takes one or more arguments (although a<br />

few functions don’t use any arguments). The function does some behind-thescenes<br />

calculations using those arguments, and then it returns a single value.<br />

The same goes for Function procedures that you develop with VBA.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!