Page 752 - Excel 2013 All-in-One For Dummies
P. 752

734 Using the Visual Basic Editor
2. Choose Insert➪Module on the Visual Basic Editor menu bar.
Excel responds by opening a new, blank Code window in the Visual Basic Editor window and by adding another Module icon (named with the next available number) in the outline in the Project Explorer window under the appropriate VBA Project.
Next, you begin your macro by creating a subroutine (all macros, even the ones you record in the spreadsheet, are really Visual Basic subroutines). To do this, you just type sub (for subroutine).
3. Type sub and then press the spacebar.
Now, you need to name your new macro, which you do by naming your subroutine. Remember that in naming your new macro (or a subroutine), you follow the same rules as when naming a range name (begin with a letter and no spaces).
4. Type the name of your macro and then press the Enter key.
As soon as you press the Enter key, the Visual Basic Editor inserts a closed pair of parentheses after the macro’s name, a blank line, and an End Sub statement on its own line below that. It then positions the inser- tion point at the beginning of the blank line between the lines with the Sub and End Sub statements. It’s here that you enter the lines of code for the macro that you’re writing.
5. Enter the lines of VBA code for the macro in between the Sub and End Sub statements.
Before you begin writing the VBA statements that your macro is to execute, you should first document the purpose and functioning of this macro. To do this, type an apostrophe (‘) at the beginning of each line of this text to enter it as a comment. (Excel knows not to try to execute any line of code that’s prefaced with an apostrophe.) When you press the Enter key to start a new line that begins with an apostrophe, the line of text turns green, indicating that the Visual Basic Editor considers it to be a comment that’s not to be executed when the macro runs.
After you document the purpose of the macro with your comments,
you begin entering the statements that you want the macro to execute (which must not be prefaced by apostrophes). To indent lines of code to make them easier to read, press Tab. If you need to outdent the line, press Shift+Tab. For help on writing VBA code, refer to the VBA online help and Steve Cummings’s excellent VBA For Dummies (Wiley). When you finish writing the code for your macro, you need to save it before you test it.
6. Choose File➪Save on the Visual Basic Editor menu bar or press Ctrl+S.
After you save your new macro, you can click the View Microsoft Excel button on the Standard toolbar to return to your worksheet where you can try it. To run the new macro that you’ve written, choose View➪Macros on
 




















































































   750   751   752   753   754