Creating a basic procedure in the code window of the Editor
In this recipe, we will create a basic procedure in the code window of the Editor. We're at the point where everything is coming together now; you know the different components, and you know how to create a module. All that's left is to create code – a simple Sub procedure – in the newly created module.
Getting ready
Make sure that you've created a module in the VBA Editor. The module should be visible as an object in the Project window, and the title bar of the code window should display the name Module1 (Code). If you cannot see the title bar, click on the restore window button to make the window smaller.
How to do it…
Let's go through the steps for this recipe:
- In the code window, type the following code:
Sub MyName() MsgBox "My name is Yourname" (Replace Yourname _ with your first name.) End Sub
- Press Alt + F11 to switch to Excel.
- Click on any cell of the active sheet. Go to Developer | Code, and click on the Macros icon. The Macro dialog box appears:
The only available macro is the one that you've just created; MyName. Click on the Run button.
A message box will appear with the words My name Mike, as shown:
A much shorter way to execute the code is to press F5 while in the VBA Editor. You will automatically switch to Excel, where the message box will be displayed.
How it works…
Entering code in the VBA Editor is relatively simple, on the condition that you have a basic understanding of VBA coding. Looking at a few code samples online before going solo is advisable, and will save you many hours of frustration.
As a bonus, the Editor will make adjustments to the text you enter. The first example of this is when you type the Sub
statement and the name of your procedure. When you press Enter, the Editor automatically inserts the End Sub
statement. As we progress, you will see how spaces are inserted, and how capitalization and text colors are changed.
Once your code is error-free, the code can be run. In this case, the outcome is a message box, displaying the words My name Mike.