30.04.2017 Views

4523756273

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

130<br />

Part III: Programming Concepts<br />

The rest of this chapter clarifies the differences and (I hope) convinces you<br />

of the value of using functions in your VBA code.<br />

Using Built-In VBA Functions<br />

VBA provides numerous built-in functions. Some of these functions take arguments<br />

and some do not.<br />

VBA function examples<br />

In this section, I present a few examples of using VBA functions in code. In<br />

many of these examples, I use the MsgBox function to display a value in a<br />

message box. Yes, MsgBox is a VBA function — a rather unusual one, but a<br />

function nonetheless. This useful function displays a message in a pop-up<br />

dialog box. For more details about the MsgBox function, see Chapter 15.<br />

A workbook that contains all the examples is available at this book’s Web site.<br />

Displaying the system date or time<br />

The first example uses VBA’s Date function to display the current system<br />

date in a message box:<br />

Sub ShowDate()<br />

MsgBox Date<br />

End Sub<br />

Notice that the Date function doesn’t use an argument. Unlike worksheet<br />

functions, a VBA function with no argument doesn’t require an empty set of<br />

parentheses. In fact, if you type an empty set of parentheses, the VBE will<br />

promptly remove them.<br />

To get the system time, use the Time function. And if you want it all, use the<br />

Now function to return both the date and the time.<br />

Finding a string length<br />

The following procedure uses the VBA Len function, which returns the length<br />

of a text string. The Len function takes one argument: the string. When you<br />

execute this procedure, the message box displays 11 because the argument<br />

has 11 characters.

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

Saved successfully!

Ooh no, something went wrong!