Page 7 of 24PREVNEXT

Get in the loop with Excel macros

Adding some code to the new macro

Code makes the macro effective.

Suppose you'd followed these steps and created a macro. Because there's nothing between your Sub line and your End Sub line, your new macro wouldn't actually do anything. You'd need to add code to bring your macro alive. Here's an example. Say you wanted to show a simple message. Between the Sub line and the End Sub lines, you would type:

MsgBox "My first macro."

While MsgBox may look like a typo, this is the VBA word for a message box. Because VBA is very literal, you must type exactly what appears above, and it's important to include the quotation marks around the rest of the text in this line of code. If you ran this macro, Excel would show a message containing My first macro and an OK button, which would close the message. In the practice that's coming up next, you'll get a chance to write and run this macro.


A great way to create your own code example is to record a macro for the action first. On the Tools menu, point to Macro and select Record New Macro. Once you've recorded the macro, take a look at it in the Visual Basic Editor to see how its code works. On the Tools menu, point to Macro and then select Macros to find the one you recorded. Select it and click Edit to see the code.

Page 7 of 24PREVNEXT