Beruflich Dokumente
Kultur Dokumente
Any other company name, brand name, product name or logo mentioned or
illustrated in this publication may be a registered trademark or trademark of its
respective owner.
More Information:
To learn more about becoming a Microsoft Office Specialist, visit
www.microsoft.com/officespecialist.
To learn about other Microsoft Office Specialist approved courseware from SVI
Training Products, Inc., visit www.svitrain.com.
The availability of Microsoft Office Specialist certification exams varies by application, application version and language.
Visit www.microsoft.com/officespecialist for exam availability.
Microsoft, the Microsoft Office Logo, PowerPoint, and Outlook are trademarks or registered trademarks of Microsoft
Corporation in the United States and/or other countries, and the Microsoft Office Specialist Logo is used under license from
owner.
The standard Windows Copy and Paste procedure is available when you are working
in the Visual Basic Editor. For example, a block of code in one macro can be copied
onto the Windows Clipboard, pasted into another macro (even if it is in a different
workbook) and edited, as necessary.
Using the File, Print command to print macro instructions can be an effective aid in
understanding the various Visual Basic statements.
When you record a command that displays a dialog box, each option in that dialog
box is included in the macro, whether or not the option has been reset. The macro
instructions listed on the following page, for example, are the result of choosing the
File, Page Setup command and selecting options to 1) print the data in landscape
orientation, 2) center the data horizontally and vertically on the page, and 3) add the
custom left-aligned header "Company Confidential."
Many lines in this macro (those that are underlined) serve no useful purpose and may
even slow down macro execution. You can, however, either delete these unnecessary
lines or precede each with an apostrophe ('). (The latter technique marks the lines as
comments, which will be ignored when you run the macro.)
Sub PageSetup( )
With ActiveSheet.pageSetup
.PrintTitleRows = ""
.PrintTitleColumns = ""
End With
ActiveSheet.pageSetup.PrintArea = ""
With ActiveSheet.pageSetup
.LeftHeader = "Company Confidential"
.CenterHeader = ""
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
.LeftMargin = Application.InchesToPoints(0.75)
.RightMargin = Application.InchesToPoints(0.75)
.TopMargin = Application.InchesToPoints(1)
.BottomMargin = Application.InchesToPoints(1)
.HeaderMargin = Application.InchesToPoints(0.5)
.FooterMargin = Application.InchesToPoints(0.5)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 300
.CenterHorizontally = True
.CenterVertically = True
.Orientation = xlLandscape
.Draft = False
.PaperSize = xlPaperLetter
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = 100
.PrintErrors = xlPrintErrorsDisplayed
End With
End Sub
Excel provides several methods for debugging a macro and correcting errors.
1) Compile Errors
Visual Basic analyzes each instruction as you enter it. If it encounters an error in
syntax, it displays a compile error message, allowing you to correct the error before
running the macro.
Some compile errors are not identified until you attempt to run a macro. In this case,
the macro instructions are displayed in Debug mode, and you are given the
opportunity to correct the error at that point.
2) Run-time Errors
If, during the running of a macro, an instruction attempts an invalid operation, Visual
Basic displays a run-time error message.
When a run-time error message appears, you have several options. You can:
Click on the Debug button. Doing this displays the macro instructions in Debug mode,
allowing you to correct the error and continue.
Click on the End button. Doing this cancels the execution of the macro instructions.
Click on the Help button. Doing this displays Help information regarding the error.
3) Step Mode
Using the Debug, Step Into command or the Step Into button on the Debug
toolbar (in the Visual Basic Editor), you can step through a macro -- that is, execute
it one line at a time. This can help to identify an error.
OPERATION YES NO
Record a personal macro
Edit a macro
(Continued)
CONCLUSION
1 CONCLUSION
You have just completed our Microsoft Office Excel 2003 Macros course. In the
course, you were introduced to many techniques. To reinforce your understanding of
these techniques, it is recommended that you read and work through this manual
once again. The manual will also serve as a valuable reference when you wish to
review any of the operations covered.
For information about any other SVI Training Products course, call 1-800-995-2798.
2. The worksheet should include the name of the country to which the data refers. Place a
combination box (in or around cell D2) that displays the following options:
Australia
France
Germany
Great Britain
New Zealand
Japan
Taiwan
U.S.A.
3. Write a macro, named GetInfo, that prompts the user for the base sales amount, the growth rate
and the inflation rate. Have the macro display a warning if the base sales amount exceeds 10,000.
Also, ensure that only a growth rate between 0% and 10% and an inflation rate between 0% and
5% will be accepted.
6. Select an option in the combination box. Then run the GetInfo macro by using the macro
button.
7. A chart representing data in this worksheet has been plotted. The following two views have also
been created:
9. Record another workbook macro, named GoToData, to display the Data view.
12. Assign the macros you have just recorded to items on the Special menu.
13. Run the GoToChart and GoToData macros by using the Special menu.
14. When you are finished, close the workbook, saving the changes.
This course has provided an introduction to the Visual Basic programming language.
You can enhance your knowledge of this language through the Visual Basic Help
system. In this section, you will learn how to:
You access the Visual Basic Help system from the Visual Basic Editor by choosing the
Help, Microsoft Visual Basic Help command or by clicking on the Microsoft
Visual Basic Help button on the Standard toolbar.
While working in the Visual Basic Editor, you can quickly obtain Help information for
the current item (for example, the statement, function or property in which the
insertion point is located) by pressing [F1].
In this exercise, you will access the Visual Basic Help system and display Help
information for Visual Basic operations.
9. Click on the Close button on the Title The Help window is closed and the
bar of the Help window. Search Results task pane is displayed.
10. Click on Open Method. Information about the Open Method is
displayed in the Help window.
11. Click on the Close button on the Title The Help window is closed and the
bar of the Help window. Search Results task pane is displayed.
12. Click on the Close button on the The Help system is exited.
Search Results task pane.
13. Close the Visual Basic Editor.
(Optional)
1. Access the Visual Basic Help system once again, and display information for topics of your
choice.
2. When you are finished, exit from the Help system, and close the Visual Basic Editor.
3.3 Summary
Display Visual Basic Help Use the Help, Microsoft Visual Basic
information. Help command or the Microsoft Visual
Basic Help button (from the Microsoft
Visual Basic window).
CREATING A
MACROS MENU
This section discusses the methods for creating your own Macros menu. In it, you
will learn how to:
This section assumes that you have recorded several personal macros, including one
named MakeSales.
With Excel, you can also assign a macro to an item on a menu. This provides still
another method for running a macro. As your macros grow in number, you may wish
to create a special Macros menu from which all or a number of them can be
accessed.
Macros Menu
On the Commands panel of the Customize dialog box, which is subsequently displayed,
select the New Menu option in the Categories box.
Drag the New Menu option from the Commands box to the Menu bar.
In this exercise, you will create a new menu. The options on this menu will be used
to run macros you have recorded.
1. Make sure that all workbooks are closed. Then open a new workbook (unless a new workbook is
already open).
4. In the Commands box, point to the A new command is added to the Menu
New Menu option. Press and hold bar.
down the mouse button, and drag
this option to the right side of the
Menu bar (just after the Help
command). Then release the mouse
button.
5. Make sure that the new command A menu is displayed.
is selected. (It should be surrounded
by a dark border.) Then click on the
Modify Selection button in the
dialog box.
You are now ready to add an item to your new menu and assign a macro to that item.
On the Commands panel of the Customize dialog box, select the Macros option in the
Categories box.
Drag the Custom Menu Item option from the Commands box to the command name
(on the Menu bar) and then to the menu that appears.
To modify the appearance of the item, click on the Modify Selection button (in the
Customize dialog box), and use the appropriate option(s) on the menu that appears.
On the Commands panel of the Customize dialog box, click on the Modify Selection
button.
In the Assign Macro dialog box, which is then displayed, select the macro name.
In this exercise, you will add an item to your new Macros menu. You will then
modify this item and assign a macro to it.
1. Make sure that the Customize dialog box is open. (The Commands panel should currently appear
in the dialog box.)
2. In the Commands box, point to the An item is added to the menu. You will
Custom Menu Item option. Press now modify it.
and hold down the mouse button,
and drag this option, first to the
Macros command on the Menu bar
and then to the empty menu that
appears below the command. Then
release the mouse button.
3. Make sure that the new menu item A menu is displayed.
is selected. Then click on the
Modify Selection button in the
dialog box.
1. The menu item added in the previous exercise is used to run a personal macro. You can also
assign a workbook macro to a menu item. When a workbook macro is run via a menu item, Excel first
opens the associated workbook if it is not currently open.
2. This subsection has discussed the methods for adding an item to a custom menu. Using similar
methods, you can also add an item to any of Excel's default menus.
This activity also demonstrates the method for removing a command from the Menu
bar.
4. Run the macro by using the new menu item (command sequence).
6. Display the Customize dialog box. Then drag the Macros command from the Menu bar into
the dialog box. (Doing this removes the Macros command from the Menu bar.)
4.4 Summary
Assign a macro to a menu item. Use the Modify Selection button on the
Commands panel of the Customize dialog
box and the Assign Macro option on the
subsequent menu.
CREATING A
MACROS TOOLBAR
This section discusses the methods for creating your own Macros toolbar. In it,
you will learn how to:
This section assumes that you have recorded several personal macros, including one
named MakeSales.
Excel, as you know, provides several methods for running a macro. For example, you
can use:
The program also allows you to assign a macro to a button on a toolbar, thereby
providing another method for running a macro. As your macros grow in number, you
may wish to create a special Macros toolbar from which all or a number of them
can be accessed.
Macros Toolbar
On the Toolbars panel of the Customize dialog box, which is subsequently displayed, click
on the New button.
In the New Toolbar dialog box, which is then displayed, enter a name for the toolbar.
In this exercise, you will create a new toolbar. The buttons on this toolbar will be
used to run macros you have recorded.
1. Make sure that all workbooks are closed. Then open a new workbook (unless a new workbook is
already open).
You are now ready to add a button to your new toolbar and assign a macro to that
button.
On the Commands panel of the Customize dialog box, select the Macros option in the
Categories box.
Drag the Custom Button option from the Commands box to the toolbar.
To modify the appearance of the button, click on the Modify Selection button (in the
Customize dialog box), and use the appropriate option(s) on the menu that appears.
On the Commands panel of the Customize dialog box, click on the Modify Selection
button.
In the Assign Macro dialog box, which is then displayed, select the macro name.
In this exercise, you will add a button to your new Macros toolbar. You will then
modify the appearance of this button and assign a macro to it.
1. Make sure that the Macros toolbar is displayed and that the Customize dialog box is open. (The
Toolbars panel should currently appear in the dialog box.)
3. In the Commands box, point to the A button is added to the toolbar. You will
Custom Button option. Press and now modify its appearance.
hold down the mouse button, and
drag this option to the new
toolbar. Then release the mouse
button.
4. Make sure that the new button is A menu is displayed (as illustrated on the
selected. (It should be surrounded following page).
by a dark border.) Then click on the
Modify Selection button in the
dialog box.
7. Click on an image of your choice. The button displays the image you have
chosen.
8. Click again on the Modify Selection Both the image and name now appear on
button. Then click on Image and the button. You will now assign a macro
Text on the menu that appears. to the button.
The button added to the Macros toolbar in the previous exercise is used to run a
personal macro. You can also assign a workbook macro to a toolbar button. When a
workbook macro is run via a toolbar button, Excel first opens the associated
workbook if it is not currently open.
This activity also demonstrates the methods for removing a button from a toolbar
and for deleting a toolbar.
6. Display the Customize dialog box. On the Macros toolbar, point to the Make Sales button.
Press and hold down the mouse button, and drag the Make Sales button into the dialog box. Then
release the mouse button. (Doing this removes the Make Sales button from the Macros toolbar.)
7. Display the Toolbars panel of the Customize dialog box. In the list of toolbars, click on the
toolbar name Macros, click on the Delete button, and then click on the OK button in the prompt box
that appears. (Doing this deletes the Macros toolbar.)
(Optional)
This subsection has discussed the methods for adding a macro button to a custom
toolbar. Using similar methods, you can also add a macro button to any of Excel's
default toolbars, as demonstrated in the next activity.
2. Add a macro button to the Standard toolbar. (To do this, drag the Custom Button option from
the Commands panel of the Customize dialog box to the Standard toolbar. Place the new button to
the immediate left of the Microsoft Excel Help button.)
3. Assign a macro of your choice to this button (by using the Modify Selection button in the
Customize dialog box).
6. Delete the new button from the Standard toolbar (by displaying the Customize dialog box and
by dragging the new button from the Standard toolbar into the dialog box).
5.4 Summary
PLACING CONTROLS
ON A WORKSHEET
With Excel, you can place graphic objects, such as combo boxes, check boxes and
radio buttons, directly on a worksheet. These objects, called controls, can then be
linked to specific areas of the worksheet, thereby simplifying data entry.
This section assumes that you know how to record a macro and assign it to a macro
button on a worksheet. It also assumes that you know how to assign a name to a
range.
Using a combo box (a combination of an edit box and list box) and/or a check box
in a worksheet is often beneficial when a particular entry must be one of a finite
number of options. In the worksheet illustrated below, for example, both a combo
box and a check box have been included for specifying the delivery method and
priority, respectively, of a shipment of goods. (The priority, in this case, is simply
true or false, depending on whether the box is selected or not.)
On the Forms toolbar, select the Combo Box button or the Check Box button.
If necessary, you can change the size and/or location of a control after placing it on a
worksheet. Simply select the control by holding down [CTRL] and by clicking on it.
Then drag any of the sizing handles that subsequently appear to resize the control,
or drag the actual control to reposition it. You can also delete a control by selecting
it and by pressing [DEL].
In this exercise, you will place a combo box and check box on a worksheet. You
will also link these controls to specific worksheet cells.
1. Make sure that all workbooks are closed. Then open the workbook named Order Processing.xls.
2. In the message box that appears (if your security level is set to Medium), click on the Enable
Macros button.
3. The worksheets in this workbook make up an order processing system. Click on the View/Enter
Sales Orders button to view the order information. (This table has been assigned the range name
OrderTable.)
4. Click on the Delivery Note Data button to display the delivery information. This is the area in
which you will place the combo and check boxes. The combo box will be used to select the delivery
method for the order, while the check box will be used to set its priority. The combo box will be linked
to a table containing the list items, as well as to the cell in which the selected item is to appear. The
check box will be linked to the cell in which the value of the box (TRUE or FALSE) is to appear.
7. Point to the combo box, and right- The Control panel of the Format Control
click the mouse button. Then click dialog box is displayed.
on Format Control on the shortcut
menu that appears.
8. Enter the specified information for When you are finished, the dialog box
the following options: should appear as illustrated below.
9. Choose the OK button. The dialog box is closed, and the control
is defined.
10. Click outside the combo box (in The box is expanded, and the list of
any blank area of the worksheet). delivery methods is displayed.
Then click on the down arrow at the
right side of the combo box.
11. Click on the second item in the list The selected option is displayed in the
(Air Express). combo box, and the number 2 appears in
cell V7.
12. Save the workbook. The changes are saved. You will now
place a check box on the worksheet.
13. Click on the Check Box button on The button is selected, and the mouse
the Forms toolbar. pointer changes to a crosshair when it is
positioned in the worksheet.
14. Create the check box by dragging When you are finished, the worksheet
the mouse pointer from the upper- should appear as illustrated below.
left corner of cell T9 to the lower-
right corner of cell U9.
15. Make sure that the check box is still The check box is relabeled.
selected.
Type: Urgent?
16. Point to the check box, and right- The Control panel of the Format Control
click the mouse button. Then click dialog box is redisplayed.
on Format Control on the shortcut
menu that appears.
17. Set the Cell link option to V9. When you are finished, the dialog box
should appear as illustrated on the
following page.
18. Choose the OK button. The dialog box is closed, and the control
is defined.
19. Click outside the check box (in any The box is checked, and TRUE is
blank area of the worksheet). Then displayed in cell V9.
click on the check box.
20. Click again on the check box. The box is unchecked, and FALSE is
displayed in cell V9.
T32: =T3
T34: =VLOOKUP(T32,OrderTable,2)
NOTE: Apply the dd/mm/yy date format to the entry in cell T34.
T36: =VLOOKUP(T32,OrderTable,3)
T37: =VLOOKUP(T32,OrderTable,4)
T39: =VLOOKUP(T32,OrderTable,4)
T41: =VLOOKUP(V7,LookupTable1,2)
T43: =IF(V9=TRUE,"Urgent","Normal")
1. With Sheet2 of Order Processing.xls displayed, enter the right-aligned label Item: in cell S45.
2. In cell T45, enter a VLOOKUP function to display the appropriate item entry in the order table.
4. In cell T47, enter a VLOOKUP function to display the appropriate quantity entry in the order
table.
6. Close the workbook (unless you wish to continue with the optional further practice that follows).
Also, close the Forms toolbar if you close the workbook.
(Optional)
1. With Sheet2 of Order Processing.xls displayed, enter the bold label Invoice Data in cell AI1.
3. Create a view, named Invoice Data, that displays this area of the worksheet.
To do this, choose the View, Custom Views command (with cell AI1 displayed in
the upper-left corner of the Workbook window and the cell pointer located in cell
AI2). In the Custom Views dialog box, click on the Add button. Then, in the Add
View dialog box, enter the view name, and choose the OK button.
4. Display the Contents screen, and record a workbook macro, named GoToInvData, to display
the Invoice Data view.
5. Redisplay the Contents screen, and add a macro button to run the above macro.
8. Set up the invoice data layout by entering the labels illustrated below.
10. In cell AK4, enter a VLOOKUP function to display the order date. (Apply the dd/mm/yy date
format to the entry.)
11. In cell AK5, enter a VLOOKUP function to display the client name. (Right-align the entry in
this cell.)
12. In the range AU1:AU4, enter the specified information into the following cells:
AU1: COD
AU2: By Check
AU3: By Credit Card
AU4: By Bank Transfer
16. In the range AK7:AL7, place a combo box. Specify the payment table (PayBy) as the input
range and cell AM7 as the cell link.
17. In the range AK9:AL9, place a check box. Change the check box label to Paid?, and specify
cell AM9 as the cell link.
19. Set up the invoice layout by entering the labels illustrated on the following page.
20. Enter the necessary formulas/functions to display the invoice information in column AK.
(Apply the appropriate formatting to the Order Date and Price entries.)
24. Close the workbook, saving any changes. Also, close the Forms toolbar.
6.3 Summary
Place a combo box on a worksheet. Use the Combo Box button (on the
Forms toolbar).
Place a check box on a worksheet. Use the Check Box button (on the Forms
toolbar).
It is assumed that you are now familiar with the methods for recording and editing
macro instructions. In this section, you will take the next step and write your own
macros "from scratch." This will not only expand your knowledge of the Visual Basic
programming language, it will greatly increase the capabilities of your macros.
When you open a workbook in this section (and in subsequent sections), a message
box may appear, depending on your current security level setting. This course
assumes that your security level is set to Medium. When this security level is in
effect and you open a workbook containing one or more macros, Excel displays a
message box regarding macro viruses, allowing you to enable or disable the macros
in that workbook. To reset the security level, choose the Tools, Macros, Security
command, select the new security level in the Security dialog box, and click on the
OK button.
The first step in writing a macro is that of creating the module in which the
instructions are to be stored.
In the Macro dialog box, which is subsequently displayed, enter a name for the macro.
In this exercise, you will open a new module in the Visual Basic Editor.
1. Make sure that all workbooks are closed. Then open the workbook named Growth Model.xls.
The InputBox function is used to prompt the user for data input during the execution
of a macro. The user's subsequent response is then entered into a specific cell.
In this exercise, you will write a macro that displays three data prompts and
enters the responses to these prompts into specific cells.
1. Make sure that a new module appears in the Microsoft Visual Basic window.
Sub GetData( )
'
' This macro displays prompts for three variables -- Region, Year1 and
' Growth -- and enters the responses into the range C3:C5.
'
Range("C3").Select
Region = InputBox("Enter Name of Region")
ActiveCell.FormulaR1C1 = Region
Range("C4").Select
Year1 = InputBox("Enter Sales Volume for First Year")
ActiveCell.FormulaR1C1 = Year1
Range("C5").Select
Growth = InputBox("Enter Growth Rate", _
Default:=0.05)
ActiveCell.FormulaR1C1 = Growth
End Sub
8. Save the workbook, and then close The changes are saved, and the
it. worksheet is cleared from the screen.
1. The Sub GetData( ) statement of the preceding macro defines the macro name. The macro, of
course, ends with an End Sub statement.
2. The next four lines are comments. It is a good idea to include comments to explain the purpose of
a macro and/or to help the user understand what a particular instruction or series of instructions
accomplishes.
3. The next instruction selects cell C3 in whatever worksheet is current when the macro is run.
4. The next instruction displays an input box that prompts the user for the region name. It also
defines a variable, named Region, for holding the response.
5. The next instruction enters the user's response into the active cell (C3).
6. The next three instructions repeat the above procedure, this time defining a variable named Year1
and displaying an input box that prompts the user for the first year's sales volume. (The response, in
this case, is entered into cell C4.)
7. The next three instructions repeat the same procedure, this time defining a variable named
Growth and displaying an input box that prompts the user for the growth rate. (The response, in this
case, is entered into cell C5.) The InputBox function in this group specifies the default value that is to
appear in the input box (0.05). Notice the underscore (_) at the end of the second line. This is used to
extend the instruction to the next line.
2. Create a macro, named GetInfo, that prompts the user for the following (and enters the user's
response into the appropriate cell):
Visual Basic includes several statements to control the flow of macro execution.
The If . . . Then statement allows you to include one or more operations in a macro
that are performed only when a certain condition is true. It is useful for such
purposes as:
Offering the user the option of performing a certain operation (for example, that of
printing the current worksheet and/or saving the current workbook).
If (Condition) Then
(Instruction or
instructions
to be executed)
End If
Structure of an If . . . Then Statement
The If . . . Then statement can include an optional Else clause, which includes one or
more alternate operations that are to performed when the condition is false.
1. Make sure that the Workbook window is clear. Then open the workbook named Growth
Model.xls.
2. In the message box that appears (if your security level is set to Medium), click on the Enable
Macros button.
1. The If Growth > 0.2 Then statement in the preceding macro instructions tests for a growth rate of
more than 20%. If the rate exceeds this value, the MsgBox function is executed, and a basic message
box with an OK button is displayed.
2. The first End If statement marks the end of the first If . . . Then statement.
3. The next instruction defines a variable, named Response, and displays a message box. The
MsgBox function in this instruction, like the first MsgBox function, specifies the message that is to
appear in the box. In addition, it specifies the buttons that are to be displayed (Yes and No) and the
box title. The buttons argument can be specified by entering the appropriate text constant (as in this
macro) or by entering the equivalent numeric constant. (The argument, in this case, could also appear
as the number 4, the numeric equivalent of vbYesNo.)
4. The next If Response = vbYes Then statement tests the user's response (in the variable Response).
If the Yes button was selected, the worksheet range A1:F16 is printed. (This instruction could also be
entered as If Response = 6 Then since the number 6 is the numeric equivalent of vbYes.)
5. The second End If statement marks the end of the second If . . . Then statement.
b) Display a message box giving the user the option of printing the worksheet.
(If the response is Yes, the range A1:H14 should be printed.)
Do . . . Loop and For . . . Next are two additional statements for controlling the
flow of macro execution. Both allow you to create macros in which operations are
"looped" -- that is, repeated a certain number of times.
Do While/Until (Condition)
(Instruction or
instructions
to be executed)
Loop
Structure of a Do . . . Loop Statement
The For . . . Next statement, on the other hand, repeats an instruction or set of
instructions a specific number of times. It is used, for example, to repeatedly prompt
the user for a finite number of entries.
In this exercise, you will use control loops in a macro. Specifically, you will enter
1) a Do . . . Loop statement to prompt the user for a single value and test the
response, and 2) a For . . . Next statement to prompt the user for four values.
1. Make sure that the Workbook window is clear. Then open the workbook named Sales
Forecast.xls.
Sub UpdateSheet( )
Range("B3").Select
InflationRate = 0
Do While InflationRate < 0.01 Or InflationRate > 0.2
Beep
InflationRate = InputBox("Enter Inflation Rate (.01 to .2):")
Loop
ActiveCell.FormulaR1C1 = InflationRate
Range("B6").Select
Beep
SalesVol = InputBox("Enter Sales Volume for First Period:")
ActiveCell.FormulaR1C1 = SalesVol
For N = 1 To 4
Beep
ActiveCell.Offset(0, 1).Range("A1").Select
SalesVol = InputBox("Enter Sales Volume for Next Period:", _
, , 50, 150)
ActiveCell.FormulaR1C1 = SalesVol
Next N
Range("C1").Select
End Sub
6500
7000
7500
8000
12. Save the workbook, and then close The changes are saved, and the
it. worksheet is cleared from the screen.
1. The third line of the preceding macro sets a variable, named InflationRate, to an initial value of
zero.
2. The Do While InflationRate < 0.01 Or InflationRate > 0.2 statement repeatedly prompts the
user for an inflation rate until the response is within the range .01 to .2. The Beep statement causes the
computer to sound a "beep."
3. The For N = 1 To 4 statement executes the following four instructions four times. N, in this case,
is a user-defined variable that serves as a counter. (The variable could have been given any other
appropriate name.)
4. The InputBox function in the For . . . Next statement is slightly different from other InputBox
functions you have seen. Notice that three commas follow the prompt. The second and third commas
are placeholders for two parameters (the title and default value for the box), which, in this case, are not
specified. The numbers 50 and 150 define the position of the box, from the left side and from the top
of the screen, respectively, ensuring that the input box will not obscure the relevant part of the
worksheet.
a) Prompts the user for the month number, repeating the prompt until the
response is between 1 and 12.
c) In turn, prompts the user for the monthly sales for each individual listed
and enters the user's response into the appropriate cell. (Make sure that the
input box does not cover the relevant part of columns A or B.)
d) Displays a message box giving the user the option of printing the
worksheet. (If the response is Yes, the range A1:C14 should be printed.)
In this section, you were introduced to three statements for controlling the flow of
macro execution -- If . . . Then ( . . . Else), Do . . . Loop and For . . . Next.
Select Case This statement executes one of two or more sets of instructions,
depending on the value of an expression. It can be used, for example,
to print one of several blocks of text, depending on user response to a
prompt.
For more information about these statements, see the Visual Basic Help system.
7.7 Summary
Open a new module in the Visual Use the Tools, Macro, Macros
Basic Editor. command and the Create button
in the Macro dialog box.
CREATING AND
USING WORKBOOK
MACROS
This section discusses the methods for creating and using workbook macros. In
it, you will learn how to:
The methods for recording and running a workbook macro are essentially the same
as those for recording and running a personal macro. When recording a workbook
macro, however, you must select either the This Workbook option, or the New
Workbook option (in the Record Macro dialog box), to let the program know that you
wish to store the macro in either the current workbook, or a new workbook, instead of
the Personal Macro Workbook.
In this exercise, you will record three workbook macros that display various
sections of a worksheet. You will examine the instructions of these macros
and then run the macros.
1. Make sure that all workbooks are closed. Then open the workbook named Regional Sales
Report.xls.
Sheet1 of this workbook includes three views (North Region, South Region and
Contents), which can be used to navigate through the worksheet. (A view is a
specific section of a worksheet that has been defined with the View, Custom
Views command.)
5. In the list of views, click on North The dialog box is closed, and the North
Region. Then click on the Show Region view is displayed.
button.
6. Click on the Stop Recording button. The Macro Recorder is turned off.
7. Using a procedure similar to that
described above, record a second
macro, named GoToSouth, to
display the South Region view.
Make sure that the Macro Recorder is
turned off when you are finished.
8. Using a similar procedure, record a
third macro, named GoToContents,
to display the Contents view. Make
sure that the Macro Recorder is
turned off when you are finished.
9. Save the workbook. You will now display the instructions of
the macros you have recorded.
10. Press [ALT] + [F8]. The Macro dialog box is displayed.
12. Close the Visual Basic Editor. The Workbook window is redisplayed.
13. Using the Tools, Macro, Macros When you are finished, make sure that
command (or the [ALT] + [F8] the Workbook Contents screen is
keyboard shortcut), run the three displayed.
macros you have recorded
(GoToNorth, GoToSouth and
GoToContents).
A macro, as you know, can be run via the menu system or via a shortcut key
combination. You can also assign a macro to a button on a worksheet and then use
that button to run the macro.
Macro Buttons
In the Assign Macro dialog box, which is displayed when you release the mouse button,
select the name of the macro that is to be associated with the button.
Button Tool
If necessary, you can change the size and/or location of a macro button after adding
it to a worksheet. Simply select the button by holding down [CTRL] and by clicking
on it. Then drag any of the sizing handles that appear to resize the button, or
drag the border of the button to reposition it. You can also delete a button by
selecting it and by pressing [DEL].
In this exercise, you will add macro buttons to the current worksheet to run
the GoToNorth and GoToSouth macros.
1. Make sure that Regional Sales Report.xls is still open and that cell A1 (of Sheet1) is selected.
2. Click on the Button tool on the The tool is selected, and the mouse
Forms toolbar. pointer changes to a crosshair when it is
positioned in the worksheet.
3. Point to the upper-left corner of A button (with the default text "Button
cell D5. Press and hold down the 1") is drawn, and the Assign Macro dialog
mouse button, and drag the mouse box is displayed (as illustrated below).
pointer to the lower-right corner of
cell E6. Then release the mouse
button.
1. With Regional Sales Report.xls open, display the data for the North Region. In an appropriate
area, add two macro buttons -- one to run the GoToSouth macro and one to run the GoToContents
macro.
2. Display the data for the South Region. In an appropriate area, add two macro buttons -- one to
run the GoToNorth macro and one to run the GoToContents macro.
4. Display the Workbook Contents screen. Record a workbook macro, named SaveBook, to save
the workbook.
5. Add a macro button to the Workbook Contents screen to run this macro.
6. Record a workbook macro, named PrintNorth, to print the data for the North Region.
7. Add a macro button to the North Region screen to run this macro.
8. Record a workbook macro, named PrintSouth, to print the data for the South Region.
9. Add a macro button to the South Region screen to run this macro.
10. Run the PrintNorth and PrintSouth macros by using the associated macro buttons.
11. Display the Workbook Contents screen, and save the workbook by using the appropriate macro
button.
12. Close the workbook (unless you wish to continue with the optional further practice that follows).
Also, close the Forms toolbar if you close the workbook.
(Optional)
1. With Regional Sales Report.xls open, record a workbook macro, named FormatDollar, to
apply the Currency with 0 decimal places format to the numeric data in both tables. Optionally,
assign a suitable keyboard shortcut to the macro.
2. Record a workbook macro, named FormatComma, to apply the Comma with 0 decimal
places format to the numeric data in both tables. Optionally, assign a suitable keyboard shortcut to
the macro.
8.4 Summary
Add a macro button to a Use the Button tool (on the Forms
worksheet. toolbar).
CREATING AND
USING PERSONAL
MACROS
This section begins by describing the two types of Excel macros. It then discusses
the methods for creating and using personal macros. In this section, you will
learn how to:
Edit a macro.
The easiest way to create any type of macro is to use Excel's Macro Recorder to
record the various operations.
In the Record Macro dialog box, which is subsequently displayed, enter a name for the
macro. (See the second note below.)
Optionally, specify a shortcut key (which can be used in combination with [CTRL] to run
the macro) and/or edit the default description.
In the Store macro in box, select the Personal Macro Workbook option, if necessary.
When you are finished, click on the Stop Recording button on the Stop Recording
toolbar.
1. You can also use the Record Macro button on the Visual Basic toolbar to display the Record
Macro dialog box (mentioned above).
2. A macro name can include letters, numbers and underscores. The first character, however, must be
a letter. (The name should not be the same as a cell reference.) Although spaces are not allowed, the
underscore character can be used to create multiple-word macro names (for example, Make_Sales). In
this course, however, you will use one-word macro names (for example, MakeSales).
In this exercise, you will record a personal macro that enters labels and
formulas into a worksheet.
2. If you are using a data diskette (instead of storing the course data files on the hard disk), insert that
diskette into the appropriate drive. Then start Excel.
3. If necessary, reset the working folder with the Tools, Options command.
4. Make sure that a blank worksheet is displayed. (Close the Getting Started task pane if it is
displayed.)
18. Click on the Stop Recording button. The Macro Recorder is turned off.
1. In the previous exercise, you assigned the keyboard shortcut [CTRL] + [m] to the macro by
entering the lowercase "m" in the Record Macro dialog box. You can, however, run the macro by
pressing either the lowercase or uppercase key (for example, [CTRL] + [m] or [CTRL] + [M]).
2. You can also assign a keyboard shortcut in the form of [CTRL] + [SHIFT] + [Letter] by entering
an uppercase letter in the Record Macro dialog box. In this case, the macro can be run by pressing
either the lowercase or uppercase letter (for example, [CTRL] + [SHIFT] + [m] or [CTRL] + [SHIFT]
+ [M]).
3. When assigning a keyboard shortcut to a macro, you should avoid using keys that are currently
assigned to specific Excel operations (for example, [CTRL] + [S], the shortcut for saving a workbook)
since the new shortcut will override the existing shortcut as long as the workbook containing the macro
is open.
You will now run the macro created in the last subsection.
In the Macro dialog box, which is subsequently displayed, select the macro name.
OR
Simply press the assigned shortcut key combination (if one has been assigned).
You can also use the Run Macro button on the Visual Basic toolbar to display the
Macro dialog box (mentioned above).
In this exercise, you will run the macro created in the last exercise. You will
perform the operation twice -- first by using the menu system and then by using the
assigned shortcut key combination.
1. Make sure that the Workbook window is clear. Then open a new workbook.
You will begin by using the menu system to run the macro.
2. Make sure that All Open The dialog box is closed, and the macro
Workbooks appears in the Macros is run. When the macro finishes its
in box and that PERSONAL.XLS! execution, the cell pointer should be
MakeSales is selected. Then click located in cell C1.
on the Run button.
3. Type: April A label is entered to identify the month of
Press [ENTER]. the report.
4. Display Sheet2. Cell A1 of Sheet2 should be selected.
You will now use the keyboard shortcut to
run the macro.
5. Press [CTRL] + [m]. The macro is run once again, this time in
Sheet2.
6. Make sure that cell C1 is selected. A label is entered to identify the month of
Type: May the second report.
Press [ENTER].
7. Save the workbook in a file named
Sales for April & May.xls.
1. Record a personal macro, named MakeProfits, that sets up the worksheet illustrated below.
Assign the shortcut key combination [CTRL] + [t] to the macro.
Notice that the worksheet includes special number formatting, font changes and
borders. The range B9:F9 contains SUM functions to total the data in each
column. When the macro finishes its execution, the cell pointer should be located
in cell D1.
2. When you are finished, close the workbook, without saving it. Then open a new workbook.
3. Using the menu system, run the MakeProfits macro in Sheet1 of the workbook.
5. Using the shortcut key combination, run the same macro in Sheet2 of the workbook.
All Excel macros consist of a series of instructions written in the Microsoft Visual
Basic for Applications programming language (hereafter referred to as simply
"Visual Basic"). Although you do not need to know anything about this language to
record a macro, there may be times when you will want to modify one or more
operations performed by a particular macro. If you are familiar with Visual Basic, you
can make necessary modifications to a macro (without re-recording it) by displaying
and editing the macro instructions.
Macro Instructions
To examine the instructions of a specific personal macro, you must first open (unhide)
the Personal Macro Workbook (Personal.xls).
In the Unhide dialog box, which is subsequently displayed, select the PERSONAL.XLS
(or PERSONAL) option, if necessary.
When you are finished working in the Personal Macro Workbook, you should once
again hide it by choosing the Window, Hide command. Also, when you exit from
Excel and are asked if you would like to save the changes to the Personal Macro
Workbook, you should select the Yes option. Otherwise, the Personal Macro
Workbook will appear automatically the next time you start Excel.
Once you have opened the Personal Macro Workbook, you can display the desired
macro instructions in the Visual Basic Editor.
To open the Visual Basic Editor (and display the instructions of a specific
macro):
In the Macro dialog box, which is subsequently displayed, select the macro name.
You can also use the Tools, Macro, Visual Basic Editor command or the Visual
Basic Editor button on the Visual Basic toolbar to open the Visual Basic Editor.
In this exercise, you will unhide the Personal Macro Workbook. You will then
print and examine the various instructions of your MakeSales macro.
2. Make sure that PERSONAL.XLS (or The dialog box is closed, and the
PERSONAL) is selected. Then click Personal Macro Workbook is opened. You
on the OK button. will now open the Visual Basic Editor.
All personal macros recorded during the current work session are stored in a single
module. You can switch from one module to another by selecting the module name
on the Window menu or by double-clicking on the module name in the Project
Explorer window. (To redisplay this window if it has been closed, choose the View,
Project Explorer command or click on the Project Explorer button on the
Standard toolbar.) You can copy code from one module to another by using the
standard Copy and Paste procedure. You can also delete a module, if necessary.
You can edit a macro by modifying the current instructions, by inserting new
instructions and/or by deleting instructions.
In this exercise, you will edit your MakeSales macro. Specifically, you will have
the macro enter the title Monthly Sales (instead of Sales Data) in a 12-point font
(instead of a 14-point font). You will also have it enter the name of one additional
sales representative.
1. Make sure that the instructions of the MakeSales macro appear in the Microsoft Visual Basic
window.
Current instructions:
Range("A8").Select
ActiveCell.FormulaR1C1 = "Bill Brown"
Range("A9").Select
ActiveCell.FormulaR1C1 = "Total"
Range("A9").Select
Selection.Font.Bold = True
Revised instructions:
Range("A8").Select
ActiveCell.FormulaR1C1 = "Bill Brown"
Range("A9").Select
ActiveCell.FormulaR1C1 = "Diana Dodd"
Range("A10").Select
ActiveCell.FormulaR1C1 = "Total"
Range("A10").Select
Selection.Font.Bold = True
Current instructions:
Range("B9").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-5]C:R[-1]C)"
Range("B9").Select
Selection.AutoFill Destination:=Range("B9:E9"), Type:=xlFillDefault
Range("B9:E9").Select
Range("C1").Select
Selection.Font.Bold = True
Revised instructions:
Range("B10").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-6]C:R[-1]C)"
Range ("B10").Select
Selection.AutoFill Destination:=Range("B10:E10"), Type:=xlFillDefault
Range("B10:E10").Select
Range("C1").Select
Selection.Font.Bold = True
5. Click on the Save PERSONAL.XLS The workbook (including the changes you
button on the Standard toolbar. have made in the macro instructions) is
saved.
6. Choose the File, Close and Return The Visual Basic Editor is closed, and the
to Microsoft Excel command. Personal Macro Workbook is redisplayed.
7. Choose the Window, Hide The Personal Macro Workbook is once
command. again hidden.
8. Open a new workbook. You will now run the revised macro.
2. Display the instructions of the MakeProfits macro in the Visual Basic Editor.
b) Enter the following item descriptions (in lieu of those it currently enters):
Model P
Model Q
Model R
Model S
Model T
c) Extend the model to six years. (This will necessitate changes in various
instructions, including those that add borders to the table.)
8. Run the revised macro, and verify the changes you have made.
When you record a macro, cell references are normally recorded as absolute. Macro
execution, as a result, always affects the same area of a worksheet, regardless of
where the cell pointer is located prior to running a macro.
There may be times, however, when you will want a macro to perform operations
relative to the initial location of the cell pointer. This can be accomplished by
selecting the Relative Reference button on the Stop Recording toolbar before
recording an operation.
In this exercise, you will record two macros -- one that includes relative cell
references and one that includes absolute cell references. You will then
compare the result of each macro when it is run.
1. Open a new workbook. Make sure that the cell pointer is located in cell A1.
You will begin by recording a macro that includes relative cell references.
6. Delete the text in cell A2. Then You will now record a macro that includes
select cell A1. absolute cell references.
7. Choose the Tools, Macro command, The Record Macro dialog box is
followed by Record New Macro. redisplayed.
8. Type: AbsMacro1 The macro name is entered, and the
Choose the OK button. Macro Recorder is turned on. Notice that
the Relative Reference button is still
selected.
9. Click on the Relative Reference The button is deselected. Therefore, cell
button. references will once again be recorded as
absolute.
10. Press [DOWN ARROW]. Text is entered into cell A2.
Type: Test Data
Press [ENTER].
11. Click on the Stop Recording button. The Macro Recorder is turned off.
12. Delete the text in cell A2. Then You will now run the macro you have just
select cell D8. recorded.
13. Using the Tools, Macro, Macros The text "Test Data" is entered into cell
command, run the macro named A2.
AbsMacro1.
14. Select cell D8. You will now run the previous macro you
recorded.
18. Click on the Close button on the Title The Visual Basic Editor is closed, and the
bar of the Microsoft Visual Basic Personal Macro Workbook is redisplayed.
window.
19. Hide the Personal Macro
Workbook.
2. Select cell A1. Record a macro, named RelMacro2 that enters the specified labels into the
following cells (recording the cell references as relative):
4. Select cell A1. Record another macro, named AbsMacro2, that enters the labels specified in step
2 into the same cells (recording the cell references this time as absolute).
6. Run both macros with the cell pointer initially located each time in cell D10.
9.8 Summary
Open the Visual Basic Editor. Use the Tools, Macro, Macros
command and the Edit button
in the Macro dialog box.
Include relative cell references in Use the Relative Reference button (on
a macro. the Stop Recording toolbar).
INTRODUCTION
10 INTRODUCTION
Welcome to this one-day Microsoft Office Excel 2003 Macros course. The primary
objective of the course is to broaden a user's knowledge of Microsoft Office Excel
2003, hereafter referred to as simply "Excel," in most cases. More detailed objectives
are listed later in this section.
An installed printer.
Some experience in working with Excel is also required. In particular, you should be
able to:
Perform basic worksheet editing operations, such as copying and moving cell
entries, clearing cells, and inserting rows and columns.
Edit a macro.
A number of conventions are used in this manual. Please be sure that you
understand them.
The course is divided into sections. Most sections consist of an introduction and
various subsections.
Exercises are presented in two columns, with each step clearly numbered. Your
instructions are in the column headed ACTION (You Do); the second column headed
COMPUTER RESPONSE / Comments describes the program response and/or may
include other comments. Be sure to complete each step in the order shown.
Example 1
This means that you should select the File command on the Menu bar.
Example 2
This means that you should first select the File command on the Menu bar and then
select the Open option on the File menu.
Example 3
When a shortcut button is available for a command sequence, that button is usually
indicated.
This means that you should position the mouse pointer on the Print button and then
click the mouse button. (When clicking on any command, button or other screen
object, or when dragging a screen object, use the left mouse button unless otherwise
instructed.)
Example 4
This means that you should type the words Department Budget and then press the
[ENTER] key. (In such instructions, special keys, such as [ENTER], [ESC] and [F1], can
be easily identified because they are always enclosed in square brackets.)
Example 5
When you are required to press two keys at the same time, the + sign is used.
This means that you should press the [CTRL] key and, while holding it down, press
the letter O.
At several points throughout the course, Further Practice activities are provided.
These have been included to enable you to review techniques you have learned.
Again, follow the instructions carefully. If necessary, refer to any notes you may have
taken as you work through these activities.
This course assumes that you are using a mouse. Basic mouse techniques are
summarized below.
ACTION DESCRIPTION
Point Position the mouse pointer on the specified screen item.
Click Press and release the left mouse button.
Double-click Press and release the left mouse button two times in rapid
succession.
Right-click Press and release the right mouse button.
Drag Move the mouse pointer from its initial position to another area of
the screen while holding down the left mouse button.
1. This course assumes that all default Excel settings are in effect when you start the program.
2. The course also assumes that the security level is set to Medium. (The security level can be reset,
if necessary, in the Security dialog box, which is displayed by choosing the Tools, Macro, Security
command.)
3. What appears on your screen may sometimes vary slightly from what is shown in this manual.