Previous  Home  Next

Let's CODE!

And finally ... the moment you've been waiting for ...
Lets make CODE! VB stores code in several different ways. The most common is called a "Module".

Now click in the main code window under "Option Explicit" and type this:

Sub HelloWorld()
' Displays a message box with a message to the world
' Input:     None
' Last edited:  13 Sept 2004 by SR
' Reason:  New

     MsgBox("Hello World")

End Sub

The first line tells VB that you're starting a new subroutine. Most code in modules is divided up into functional units called Subroutines or Functions. You'll learn more about the difference later.

The next few lines that start with apostrophes are comments. You can drop these in pretty much wherever you like.

Good Programming Practice

Use LOTS of comments. They don't slow down your code but they'll make it a lot easier to remember what your code does and why.

Comment each subroutine and function with a description of what it does and what input and output it takes.
If it depends on other subroutines or functions, it's a good idea to mention that in comments also.

Recording the last edited date, the person who did the edit and the reason for it can also be very useful when you're working on a project that involves multiple programmers.

The next line is the one that does the work: it displays a standard Windows message box with the text "Hello World" in it and waits for you to click OK.

VB filled in the "End Sub" line for you automatically, as soon as you typed the first Sub xxx() line.
Any code after the End Sub isn't part of the subroutine and won't run.

OK. Are you ready for The Big Moment?

Click anywhere in your code then press F5 or choose Run, Run Sub/UserForm from the main menu bar.

Zow. Was that exciting or what?

What, right? If everything went according to plan, it displayed a message box that said "Hello world". Big whoop.

But wait, there's more. Lots more. This was just a test to make sure that everything was set up right and working correctly. Now we're ready to move along to the next section.

But first, another tip:

Good Programming Practice

Don't accept VB's default name for new modules. Click the module name and in the Properties window below, change the name to something that indicates what the code in the module does. Here I've renamed the default "Module1" to "modMyFirstVBA".

screen shot of renaming a module

Now, click Next to move along to the next section where you'll learn what all those windows and panes and things in the IDE are for.

Previous  Home  Next