Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 99

TIP

Оглавление

F5 is a shortcut for the Run ➪ Run Sub/UserForm command.

When you enter the code listed in step 5, you might notice that the VBE makes some adjustments to the text you enter. For example, after you type the Sub statement and press Enter, the VBE automatically inserts the End Sub statement. And if you omit the space before or after an equal sign, the VBE inserts the space for you. Also, the VBE changes the color and capitalization of some text. This is all perfectly normal. It's just the VBE's way of keeping things neat and readable.

If you followed the previous steps, you just created a VBA Sub procedure, also known as a macro. When you press F5, Excel executes the code and follows the instructions. In other words, Excel evaluates each statement and does what you told it to do. You can execute this macro any number of times—although it tends to lose its appeal after a few dozen executions.

This simple macro uses the following concepts:

 Defining a Sub procedure (the first line)

 Declaring variables (the Dim statements)

 Assigning values to variables (Msg and Ans)

 Concatenating (joining) strings of text (using the & operator)

 Using a built-in VBA function (MsgBox)

 Using built-in VBA constants (vbYesNo, vbNo, and vbYes)

 Using an If-Then construct (twice)

 Ending a Sub procedure (the last line)

As mentioned previously, you can copy and paste code into a VBA module. For example, a Sub or Function procedure that you write for one project might also be useful in another project. Instead of wasting time reentering the code, you can activate the module and use the normal copy and paste procedures (Ctrl+C to copy and Ctrl+V to paste). After pasting it into a VBA module, you can modify the code as necessary.

Alternatively, you can right-click your module and select the Export File option. This allows you to save your module as a .bas file. Once you have your .bas file, you can open another workbook, open the VBE, and then choose File ➪ Import File to import the saved .bas file.

Excel 2019 Power Programming with VBA

Подняться наверх