0x00 如何创建一个宏
Developer Tab | Command Button | Assign a Macro | Visual Basic Editor |
With Excel VBA you can automate tasks in Excel by writing so called macros. In this chapter, learn how to create a simple macro which will be executed after clicking on a command button. First, turn on the Developer tab.
Developer Tab
To turn on the Developter tab, execute the following steps.
- Right click anywhere on the ribbon, and then click Customize the Ribbon.
-
Under Customize the Ribbon, on the right side of the dialog box, select Main tabs (if necessary).
-
Check the Developer check box.
-
Click OK.
-
You can find the Developer tab next to the View tab.
Command Button
To place a command button on your worksheet, execute the following steps.
-
On the Developer tab, click Insert.
-
In the ActiveX Controls group, click Command Button.
- Drag a command button on your worksheet.
Assign a Macro
To assign a macro (one or more code lines) to the command button, execute the following steps.
-
Right click CommandButton1 (make sure Design Mode is selected).
-
Click View Code.
The Visual Basic Editor appears.
-
Place your cursor between Private Sub CommandButton1_Click() and End Sub.
-
Add the code line shown below.
Note: the window on the left with the names Sheet1 (Sheet1) and ThisWorkbook is called the Project Explorer. If the Project Explorer is not visible, click View, Project Explorer. If the Code window for Sheet1 is not visible, click Sheet1 (Sheet1). You can ignore the Option Explicit statement for now.
-
Close the Visual Basic Editor.
-
Click the command button on the sheet (make sure Design Mode is deselected).
Result:
Congratulations. You’ve just created a macro in Excel!
Visual Basic Editor
To open the Visual Basic Editor, on the Developer tab, click Visual Basic.
The Visual Basic Editor appears.