Access VBA Macro Programming

(Joao Candeias) #1

Your First Access VBA Macro


Programming books traditionally help direct your first steps in a program by writing a simple
piece of code to display the text “Hello world,” and this book is no exception. You will use
theMsgBoxstatement to display the statement. This is a simple user interface showing the
statement and an OK button that you have probably seen before in Windows.
Under the statementSub MyCode()but beforeEnd Sub, type inmsgbox "Hello
World". Be sure to be lazy and do not use theSHIFTkey when typingmsgboxand see what
happens. The word “msgbox” transforms into the upper- and lowercase “MsgBox” because it
is a defined statement word in VBA and is already set up to appear this way. However, you
must make sure you spell it correctly—make a mistake, and you will get a compile error.


Private Sub MyCode()
MsgBox "Hello World"
End Sub


Notice that theMsgBoxstatement is indented with theTA Bkey. This is a useful way to see
where one set of statements begins and ends. Without this notation, it is easy to get lost and
lose track of where a loop starts and finishes when complicated loops are used. For more on
loops, see Chapter 4.
AMsgBoxstatement is a simple way to provide an interface to the user by displaying a
message and an OK button. I’m sure you’ve seen message boxes like this pop up from time to
time, and now you know how easy they are to create. They can be quite sophisticated, and
Chapter 5 explains in more detail how to use them.
After you type in the wordmsgbox, a box containing all the parameters for this command
is displayed. In this instance, you do not have to take any notice of this box since you are
only displaying a text string. However, it can be extremely useful in telling you what
parameters are required for a function and in what order they should appear. If, for example,
you wanted to give the message box an icon or a title, the parameter box would help you do
this correctly. The parameter box is a list box that appears when you reach the parameter for
the icon and gives a list of optional constants for the icon of your choice. This type of help is
available for all functions when using the VBA editor. Your code window should now look
like Figure 1-5.
You can now run your code, which can be done in one of three ways:


 Click your mouse anywhere on your code (MyCode) and then click the Run icon in the
VBE toolbar—this is a green triangle pointing to the right-hand side.
 PressF5.
 Click Run | Run Sub/UserForm from the VBE menu.

Chapter 1: The Basics 9

Free download pdf