0 ratings0% found this document useful (0 votes) 92 views82 pagesExcel VBA Programming - 02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Excel 2000 Programming Working with Conditional Statements
'g with Conditional
ents
‘Understanding conditional statements
Working with decision stuctures
Working with looping structures.Excel 2000 Programming Working with Conditional Statements.
Understanding Conditional Statements
Conditional statements form loops or control decisions in a program. The most
common structures in Visual Basic are:
Then Single-line Decision Structure that conditionally: °
executes the embedded code.
1f..Then|...Else]...End If Block Decision Structure that conditionally executes |
the embedded code.
Do [While[Until]..Loop Block Loop:Structure that! conditionally executes the
‘embedded code while or until a condition is true.
For...Next Block Loop Structure that conditionally executes the”
‘embedded code. .
Select Case..End Select. Decision Structure that conditionally. executés the:
embedded code.
GoTo, GoSub Branch Structure that unconditionally sends control
toa line of sub procedure.
On...GoTo, On...GoSub Branch Structure that conditionally sends control to
a line or sub. procedure.
‘The IF and DO statements execute the code conditionally. The DO statement will
cycle repeatedly while the condition is satisfied. FOR Joops are used to cycle
through code a specific number of times. The SELECT CASE is an alternative to
nesting several IF statements to test complex conditions.
In the case you develop a conditional statement that results in an endless
Joop of execution, press to stop execution of the code.
Tivee statements that are useful in halting program execution are:
Stop suspends or pauses éxccution without unloading anything
from memory.
End terminates an application and unloads it from memory.
Exit keyword provides a way to exit a Joop structure or procedure without
satisfying the test condition. If found in a control structure,
execution will resume after the last line of the structure.
(¢.g., an Exit Do will jump the control to the next line after
the Loop statement).
62Excel 2000 Programming Working with Conditional Statements,
Working with Decision Structures
In an event-driven application, it is important to be able to handle user feedback and
make decisions on how to branch program control based on a given condition.
Conditional statements in Visual Basic first test a condition and then execute code
‘Segments depending upon the test's results. There are two decision structures
available to the programmer in Visual Basic: the If... Then (Else) and the Select Case
structures,
H..Then...lse Structure
The If-.-Then..Else structure is used to execute one or more statements depending
upon the test condition. There are two forms of the If...Then construct.
The single line statement may be used when only one statement is to be executed
upon a successful test condition. The syntax of the single line If.. Then..Else
statement is as follows:
If Then [Else }
If EmpLevel > 5 Then EmpTax =
Else EmpTax = 24
‘The above example will set EmpTax to 0.4 if the condition is true (EmpLevel is more
than 5); otherwise, EmpTax will be set to 0.24.
‘The easier-to-read syntax for a multi-line If...Then...Else statement follows:
If Then
Istatement_block_1}
[Else
{[statement_block_n\}
EndIf
If Country = "US" Then 5:
‘Account = “Domestic”
Rate = 0.40
Else
Using the multi-line syntax allows for multiple statements within your conditional
structure. Plus, itis easier to document and decipher.
‘The test condition is generally TRUE/FALSE in nature, but any expression that can
be evaluated as numeric is valid. Logical expressions evaluate to 0 or Null for False
and a non-zero number for True.
63Excel 2000 Programming Working with Conditional Statements.
Working with Decision Structures, continued:
‘When executed, the first condition is tested and, if it is trac, the code following the
Then statement is executed. If the test is false, the code following the Else statement
is executed. Ifno Else statement is found, the code after the End If is executed,
To perform multiple tests, include an Elseif...Then statement after the initial If. Then
clause. With this structure, after the If statement is tested, if it proves false, the
program will test the Elseif statement. If't is true, its code will be executed. If it is
false, it will look for the next Elseif or Else statement and test or execute as needed.
This structure is very difficult to decipher and even more difficult to code. In
situations with multiple tests a better option is the Select Case Structure.
Select Case Structure
The Select Case structure (also called case statements) is often used in place of
complex IF structures. If you see the need for more than one Elseif statement, you
should consider a Case structure. One major advantage of this construct over the
If. Then...Else structure is that your code will be more readable and efficient
The Select Case structuse contains only one test expression, in the first line of the
structure, Each Case statement in the Seléct Case structure is then compared against
the test expression, and if a match is found, the statements accompanying the Case
are executed. Only the statement block of the first matching Case expression is
executed. A Case Else statement may be added at the end of the structure to execute
if none of the Case expressions evaluates to True.
‘The syntax of the Select Case structure is shown below:
Select Case
Case
Case
Case
[Case Else
‘)
End Select
Select Case Score. Text
Case 0
Result.Text = “Fail”
Case 1 t0 50
Result. Text = "Below Average"
Case > 50
Result. Text = "Above Average”
Case Else
Result.Text = “Iregular Score”
| End Select
aoeExcel 2000 Programming Working with Conditional Statements
2S Case Select Statements
1. Open the NEW INVENTORY workbook.
2. Add the following function to a module in that workbook:
Try It
Function GetColor(VinNum)
Dim ColorMarker as String
ColorMarker = Mid(VinNum, 12, 1)
Select Case ColorMarker
Case 0
GelColor = "Black*
Case 1
GetColor = White”
Case 2
GelColor = "Silver"
Case 3
. GelColor = “Green”
Case 4
GelColor = “Blue”
Case 5
GetColor = “Red”
Case 6
GetColor = “Yellow”
Case Else
GetColor = “Unknown”
End Select
End Function
continued on next pageExcel 2000 Programming Working with’ Conditional Statements
Case Select Statements, continued
3. Add the selected text to the BringEmIn sub procedure:
Option Explicit
Public VinNum As String
‘Sub BringEming
Dim DealerCost As Single
Application Run "Personal.xis!ReceiveCars”
Application. Run “Personal xis!MoveCells”
Range("Az’).Select
VinNum = ActiveCell, Value
ActiveCell.Offset(, 5).Value = GetColor(VinNum)
Range("G2").Select
dealercost = ActiveCell, Value
ActiveCell.Offset(, 1).Value = GetMsrp(DealerCost)
Application.Run "Personal xls!Formatlt”
End Sub
4. Select a blank workshicet and run BringEmJn,
5. Open the VB Editor and place the cursor on the last line in the code window of
the module in New Inventory that contains GetColor.
6. Open the Insert menu in the VB Editor and select File.
7. Navigate to the student data directory and select Case Statements. .
8. Click Open.
9. Create code that calls the functions that add the Year, Make, Model, and
Classification to the worksheet. Be sure to call the functions by names already
established (GetY ear, GetMake, GetModel, and GetClassification). If you need
help, the finished code appears on the next page.
10. Delete the contents of a worksheet and run BringEmln to make sure it works
correctly,
11. Save the workbook.
continued on next pageExcel 2000 Programming Working with Conditional Statements
Case Select Statements, continued
Option Explicit
Public VinNum As String
Sub BringEming
Dim DealerCost As Single
Application Run *Personal.xls!ReceiveCars”
Application Run "Personal xts!MoveCelis”
Range(AZ*) Select
VinNum = ActiveCell, Value
GetYear(VinNum)
GetMake(VinNum)
ActiveCell. Offset(, 1). Vatu
AdtiveCell Offset(, 2). Value
ActiveGell Offset( 3). Valu
ActiveCell Offset(, 4).Value
ActiveCell Offset(, 5). Value
‘etClassification(VinNum)
GetColorVinNum)
Range("G2") Select
DealerCost = ActiveCell Value
ActiveGell.Offsel(, 1), Value = GetMsrp(DealerCost)
Application.Run "Personal.xls!Formatit”
End SubExcel 2000 Programming Working with Conditional Statements,
Working with Looping Structures
A looping structure can be used to execute code repetitively. ‘There are two types of
simple looping structures in Visual Basic: the Do...Loop and the For... Next loop.
Do...Loop Structure
The Do...Loop structure comes in two flavors: Do While and Do Until. The Do
While structure will execute a code block as long as a given condition is true. ‘The
Do Until structure will execnte a code block up to the point when a given condition
‘becomes true (or as Jong as the condition is false).
4 Further, you can decide to test the condition either before or after the code block is
executed by moving the While or Until keyword to the beginning or end of the
structure.
“The syntax for the Do... Loop structure is shown below:
Do [While/Until ]
Loop.
Do While count <5
Do :
]
Loop Until count = 5
In the above examples, the code block will be executed as Jong. as count is less than
five. In the first example, the code will be run only if the condition is true. In the
second example, the code will be run and then the condition wall be tested to see if it
should loop again.
While and Until can both be used at the beginning os end of a loop, as long as they
make a valid expression.
68Excel 2000 Programming Working with Conditional Statements
Try It
Working with Looping Structures
In this exercise we are going to complete the BringEmln sub procedure which if you
‘recall puts data into the same format as the inventory sheet. Once BringEmIn works
correctly, we arc going to add the edited data to the end of the inventory sheet.
1. Edit BringEmIn so that it matches the code shown below:
Option Explicit
Public VinNum As Stiing
‘Sub BringEming,
Dim DealerCost As Single
Application.Run "Personal xls!ReceiveCars”
Application. Run "Personal xls!MoveCelis”
Range(A2") Select
‘VinNum = ActiveCell. Value
Do
ActiveCell.Offset(, 1) Value = GetYear(VinNum)
ActiveCell Offsel( 2). Value = GetMake(VinNium)
ActiveCell.Offsel(, 3).Value = GelModel(VinNum)
ActiveCell.Offsel(, 4).Value = GetClassification(VinNum)
ActiveCell Offset(, 5). Value = GetColor(VinNum)
DealerCost = ActiveCell.Offset(, 6).Value
AcliveCell Offsel(, 7).Value = GetMsrp(DealerCost)
ActiveCell Offset(1) Select
VinNum = ActiveCell, Value
Loop Until Vin
Application.Run "Personal xis!Fomattt”
End Sub
2. Clear the worksheet and ran BringEmin.
3. Place the cursor on the last line of a module in the personal workbook.
4. Open the Insert menu in the VB Editor and select File. ~
5. Navigate to the student directory and select SendEmOut,
6. Click Open.
continued on next page
_ continued on next pageExcel 2000 Programming Working with Conditional Statements
Working with Looping Structures
7. Ifthe student data directory you are using is NOT C:Data then edit the following
Tine in SendEmOut to reflect the folder where your data exists:
Workbooks.Open FileName:="C:\Datalinventory xis"
8. Add the following line of code before the End Sub line in BringEmIn:
Application. Run "Personal xis!SendEmOut™
9. Gotoa blank worksheet in New Inventory (or clear the contents of an existing
worksheet)
10. Place the cursor on the line you just entered.
1]. In the VB Editor, Open the Debug mem and select Run To Cursor.
12. Step into the rest of the sub procedure.
13. Click Eiaf Reset
14, Save and close the workbook
7 6-10Excel 2000 Programming Working with Conditional Statements.
Working with Looping Structures , continued:
For...Next Structure
For = To [Step ]
Next []
Forx=0T0S
Total = Total + Amount(x)
Nextx
‘The default Step increment is 1. You can count backwards by specifying a Step
increment of -1.
You can use any kind of mumeric expression for the start and end values,
literals and variables.
including
An important feature of the For Joop is that it can be used to loop through a
collection. Since you may not know (or it would be inconvenier te determine) how
For each - in
Next
Oietse (86 objece)
x
For Each shest In Worksheets
EL sheet Activate
ActiveSheet protect
Next
eTExcel 2000 Programming Working with Conditional Statements
Try It
Working with the For...Next Structure
In an earlier exercise we created a sub procedure called AddTotals which placed the
total sales for a given day at the bottom of a given sheet in the Fiscal Year Sales
workbook. We are now going to create a sub procedure that automatically totals all
of the worksheets in the workbook.
1. Open the workbook FISCAL YEAR SALES.
2, Display the most recent date’s worksheet
3. Type the following sub procedure in a module in Fiscal Year Sales:
Sub AlfTotats0.
Dim Sheet As Worksheet
For Each Sheet In Worksheets
Sheet. Select
AddTotals
Next Sheet
End Sub
4, Save the workbook.
5. Run AlTotals.
6. At some point during execution you will run into an error. On days when there
were no sales, the procedure AddTotals doesn’t work correctly. This is called a
run-time error.
7, Click End.
8. Close the workbook without saving changes and open it again, displaying the
most recent date’s sheet.
continued on next page
e12
L
renExcel 2000 Programming Working with Conditional Statements,
Working with the For...Next Structure, continued
9. Add the selected code to the AddTotals sub procedure:
Sub AddTotalsQ,
Dim LastCell As Range
Dim TotalFormula As String
If Range('i2")-Value <> 0 Then
Set LastCell = Range("I2").End(xiDown)
LastCell Select
ActiveCell Offset{2, 0).Select
‘TotalFormula = “= sum((2:" & LastCell_ Address & *)"
ActiveCell. Formula = TotalFormuta
Else
Range("A3°).value = "No Sales Today”
End if
End Sub
10. Run AllTotas.
11. Save the workbook.
ae ae ates 13Excel 2000 Programming Working with Forms and Controls
Understanding Userforms i
Using the toolbox
Working with Userform properties, events, and methods
Using the Properties window |
Working with controls
7AExcel 2000 Programming Working with Forms and Controts
Understanding UserForms
Dialog boxes are commonly used in applications to interface with the user. With
‘VBA, you can create your own custom dialog boxes that can be used to display
information to or receive information from the person running your project. These
‘custom dialog boxes are referred to as UserForms. A UserForm object not only
Provides the visual interface, but also stores some or all of the code required for the
functionality of the form.
‘Typically, a UserForm serves as a container for control objects, such as labels,
command buttons, combo boxes, etc. The controls that you use will depend on what
kind of functionality you want in the form and what type of information needs to be
communicated to and from the user.
When you add a UserForm to your project, the UserForm window with a blank form
will appear, as well as a toolbox containing the available controls. Controls are
added by dragging icons from the toolbox onto the UserForm. ‘The currently selected
contfol on the form appears in a rectangle with eight handles. The handles can be
used for sizing the control. The grid of dots on the form background can help you
‘more easily place and align controls. There is an option for snapping controls to this
rid, or you can choose to place controls freely on the form.
‘The illustration below shows a UserForm with two controls - a label and a command
button in the UserForm window:Excel 2000 Programming Working with Forms and Contro's .
Understanding UserForms, continued:
‘The following is a list of useful keystrokes and key combinations that can be used in
the UserForm window:
Displays the code window for the selected form.
i i
-Displays the Properties window for the selected object: 4
2 |
Deletes the selected control. 4
j
Undoes the deletion of 4 control.
‘Moves through the controls on the form in tab order: 4
Moves through the controls in reverse tab. order,
= Click’ Selects multiple controls: +}
i |
Gii)- Click Removes a'selected contro! from a'set of sélected controls. !
Adding a UserForm to a Project '
1. Select the desired project name in the Project Explorer. !
2. To insert a form, perform one of the following:
* Open the Insert menu in the VB Editor and select UserForm.
+ Right-click the project name and select Insert, choose UserForm. 7 1
|
|
@ To display an existing form, select the UserForm object in the Project :
Explorer and click [iJ View Object; you can also right-click the UserForm. «
object and select View Object from the Shortcut menu. |
id
t
73Excel 2000 Programming Working with Forms and Controls
ing
Adding a UserForm to a Project
1. Open FISCAL YEAR SALES, if necessary.
2. Select the most recent date’s worksheet that contains data.
3. Open the VB Editor.
4. Sclect the Fiscal Year Sales project in the project window, if necessary.
5. Open the Insert menu in the VB Editor and sclect UserForm.
—.
74Excel 2000 Programming
Using the Toolbox
Working with Forms and Controls
‘The working set of controls that you can add to your forms is displayed in the
toolbox. Contsols are drawn on forms to build the desired interface and add
functionality.
Below is an illustration and explanation of the default set of controls displayed in the
toolbox
Labet
‘Text Box
Combo Box
List Box
Check Box
(Option Button
Toggle Button
Frame
Command Buitton
Tab Stip
MultiPage
Scroll Bar
Spin Button
Image
4 Ref Et
makes the mouse behave as.a pointer for
selecting a control on the form. This is not
really a control.
‘creates a box for static text.
creates a box for text input and display.
cctéates a combination ofa drop-downlist and:
text box: The user can choose an option or type:
the choice.
creates a scrollable list of choices.
creates a logical check box.
creates an option button that allows exchisive
choice fiom a set of options.
creates a toggle button that when’selectéd
indicates a yes, true, or on status.
‘creates a visual or functional border.
cexeates a standard command button.
creates a collection of tabs which can be used
to display different sets of similar information.
cexcates a collection of pages. Unlike:the Tab
Strip each page can have a unique layout.
creates a tool that can set or return a value for a
different control according to the positioning of
the scroll box on the scrolll bar.
creates a tool that increments numbers.
creates an area to display a graphical image
from a bitmap, icon, or metafile on your form.
displays the address of a range of cells selected
on one or more worksheets.
After clicking an icon in the toolbox and drawing it on the form, the toolbox selection
will revert back to Select Object. If you double-click an icon in the toolbox, the icon
will remain selected, allowing you to draw multiple controls.
75Excel 2000 Programming Working with Forms and Controls
Working with UserForm Properties, Events, and Methods
Every UserForm in a project has its own set of properties, events, and methods. You
can set properties in both the Properties window and through code in the Code
window. Methods and events are handled in the Code window.
Properties
All forms share the same basic set of properties. So, to begin with, every form will
be the same. As you alter the form visually in the UserForm Window, keep in mind
that you are also changing its propertics. For example, if you resize a form window
by dragging its borders, you are changing the Height and Width properties
The following list describes some of the more commonly used properties of a
UserForm:
BackColor sets the background color of a form.
BorderStyle ‘sets the border style for the form.
Caption sets the form's ttle in the title bar
Enabled determines whether the form can respond to user-generated
events.
Height ‘sets the height of the form.
HelpContext1D associates a context sensitive Help topic with the form.
MonsePointer. sets the shape of the mouse pointer when the mouse is
Positioned over the form.
Picture specifies graphic to display in the form by naming a bitmap,
icon, or metafile.
StartUpPosition sets the area of the screen where the form will be displayed.
Width sets the width of the form.
76Excel 2000 Programming Working with Forms and Controls
Working with Form Properties, Events, and Methods, continued:
Events
All UserForms share common events that they can detect and to which they can react
by executing a procedure. If you want to create code that executes on an event,
display the Code window for the form (making sure the form's name is selected as
the Object so you know you are dealing with its code) and then select the event from
the Procedure list. By default, when you select an event from the list, the basic event
sub procedure structure is inserted for you so you can begin typing the procedure’s
Private Sub UserForm Initialize ()
End Sub
(es sue eS
Methods,
UserForms also share similar methods that can be used to execute built-in |
procedures. Methods are normally used to perform an action on the form. When you
use a method in code, you treat it just like it was a procedure defined for an object.
The syntax is given below:
‘ObjectName.method
Member. Hide
‘The three most useful methods of a UserForm for our purposes in this course are ry
explained below: :
&
Show displays the form: can be used to load a form if it is not already
loaded :
Hide hides the form without unloading it from memory.
Unload Unloads the form from memory.
|
|
}
74Excel 2000 Programming Working with Forms and Controls
Using the Properties Window
Each type of control has a set of properties that describe the attributes of that control
(@g., the width of a text box or the caption shown on a command button). These
Properties can be set in the design environment using a scrolling editor.
‘The control or object name and type are listed in the drop-down list atthe top of the
Properties window. Select a desired object from this list to view its properties. Each
individual property may present an edit box, a drop-down list, ora dialog box for
setting values.
The categories for a property list can vary by object. Frequently used categories
include appearance, behavior, font, position, and miscellaneous.
Using the Properties Window
1. To open the Properties window, perform one of the following:
* Open the View menu and select Properties Window.
+ Press (Fa).
+ Click EH Properties Window.
2. To display the properties in alphabetical order:
* Click the Alphabetic tab.
: ; 3. To display the properties by category:
i * Click the Categorized tab.
: 4. To change a property setting:
* Select the desired object in the UserForm window or from the drop-down
list
| + Scroll to the desired property and use the appropriate method to change
the sciting in the value column. .
_O
Using the Properties Window
1. Display the Properties window.
2, Set the new form's properties as shown below:
[ RunRepors
Run Reports,
175 =|
330
3. Cloue the Properties windowExcel 2000 Programming Working with Forms and Controls
Understanding Controls \
A control is an object that is placed on a form to enable user interaction. Some
controls accept user input and some display output
‘Much like forms, controls are defined by their:
* List of property values that define the control's visual interface and
functionality.
‘+ _List of methods, which act as built-in pre-defined procedures.
+ List of events to which the control can respond by executing a user-defined
procedure. i
‘A sample window with commonly used controls is shown below:
ee
7-9Excel 2000 Programming Working with Forms and Controls
Understanding Controls, continued:
Although each type of control is unique, many share similar attributes and behaviors.
In any case, before we begin singling out specific controls for discussion, we will
first discuss their shared characteristics.
‘The following list contains some common control properties:
specifies a string to be displayed when the mouse pointer is
paused over the control.
Enabled determines if the user can access the control.
Font sets the control text typeface and size.
Height sets the height of the control.
MousePointer sets the shape of the mouse pointer when the mouse is
positioned over an object. (Arrow, I-Beam, ete.)
TabIndex determines the order in which the user will tab through the
controls of a form,
TabStop determines whether a control can be accessed via the (EBS) key.
(Control may still be accessed by the mouse.)
determines whether the object is visible. Corresponds to the
‘Show and Hide methods.
Width sets the width of the control.
ControtTipText
Most control properties can be viewed and assigned manually at design time as well
as referenced and assigned in code during execution,
‘The syntax for setting properties in code is as follows
f
‘ObjectName.property = value
Label Caption = "Heto™
Many controls can respond to the same system events. As is the case with forms, if
you want to write a procedure that executes when a control detects a particular event,
you write the code in the Code window, having selected the control's name from the
Object drop-down list. :
All controls have a default property that can be referred to by simply referencing the
name of the control. For instance, the Caption property is the default property of the
Label control making the two statements below equivalentjaca a
Excel 2000 Programming Working with Forms and Controls
Working with the Label Control
‘The Label control is used to display text that cannot be modified directly by the user
but can be modified within a procedure by assigning a new value to its Caption
Property.
‘iis "lat
The Label control is represented in the toolbox by the EB icon.
Below are some important and unique properties related to’a Label control:
TextAlign determines the alignment of the text inside the label.
AutoSize determines if the dimensions of the label will be
automatically sized to fit its caption
Caption sets the displayed text for the label. 4
WordWrap determines if a label expands horizontally or vertically as text
is added. Used in conjunction with the AutoSize property.Excel 2000 Programming Working with Forms and Controls
Try It
Working with the Label Control
Affler this exercise your form should look similar to the illustration below. As you
perform this and other exercises in this chapter, do not worry about the spacing, or
alignment.
1. Click BJ to open the Toolbox, if necessary,
2. Click EBM Label in the Controls toolbox.
3. Click in the bottom Ieft comer of the form.
4, Open the Properties window.
5. Inthe Properties Window, set the following properties:
‘AuloSize True
Caption Finish Dale:
‘Wordwrap | False
6. Create the Start Date Label and position it as shown above. Use the caption
Start Date: and change the other properties as you did with Finish Date.
7-12Excel 2000 Programming Working with Forms and Controls
Working with the Text Box Control
A Text box control allows the user to add or edit text. Both string and numeric
values may be stored in the Text property of the control.
‘The Test box control is represented inthe toolbox by the EA
Below are some important properties related to a text box:
specifies the maximum number of characters that ean be
typed into a Text Box. Default is 0 which indicates no limit.
indicates whether a Text Box can contain more than one line.
determines whether a multi-line text box has horizontal
and/or vertical scroll bars.
Text contains the string displayed in the text box.ot
Excel 2000 Programming Working with Forms and Controls
Working with the Text Box Control
After this exercise, your form should look similar to the illustration below:
Try It
: 1. Click BB Textbox.
2. Draw attext box control on the form next to the Start Date label.
3. Set the following properties to the values displayed:
Name. BeginDate
Enabled, False
Width 50
4.. Select the text box.
5. Copy the text box and paste its copy directly below it. Use the above illustration
asa gnide.
6. Change the Name property of the new text box to FinishDate, Note that the *
other property changes were carried forward to the new instance of the text box.
7A4Excel 2000 Programming Working with Forms and Controls
Working with the Command Button Control
‘Command buttons are used to get feedback from the user. In an event-driven
environment, command buttons are among the most important controls for initiating
event procedures, As.a result, the most heavily used event associated with the
‘Command Button control is the Click event,
‘The Command button control is represented in the toolbox by the
Below are two unique properties related to a Command button control
allows the [Eic) key to “click” a Command button. Can only
be set for one Command Bution per form
Default allows the [Enter] key to “click” a Command button. Can
only be set for one Command button per form.
715 }Excel 2000 Programming Working with Forms and Controls
Working with the Command Button Control
After this exercise, your form should look similar to the illustration below:
2. Draw a command button in the upper right hand corner of the form.
3. Set the following properties for the control:
] Name Display
t Caption: Display
i ‘Default Te
4. Create another command button below the first as shown.
5. Set the following properties for the control:
: Name ‘Cancel
Caption _| Cancel 7
‘Cancel True
Default False
6. Save the workbook.
TA6Excel 2000 Programming Working with Forms and Controls
Working with the Combo Box Control
A. Combo box control allows you to display a list of items in a drop-down list box.
‘The user can select a choice from the list or type an entry. ‘The items appearing. in the
list can be added in code using the control’s Additem method.
‘The Combo box control is represented in the toolbox by the {El icon.
Below are some important Combo box control properties:
ListRows sets the number of rows that will display in the list.
MatchRequired determines whether the user can enter a value that is not on
the list.
returns or sets the text of the selected row in the list,
Text
A few important methods that belong to the Combo box control are explained below:
Addltem item_name, index _adds-the specified item to the bottom of the list.
If you specify an index number after the named
item, you add the item to that position in the list.
Removeltem index removes the item referred to by its index number,
‘Clear clears the entire list
TAT
eos
==Excel 2000 Programming Working with Forms and Controls
Using the Combo Box
After this exercise, your form should look similar to the illustration below:
‘ComboBox and draw the control in the lower right comer of the form.
2. Set the following properties:
Name ‘WhichMonth:
MatchRequired | Tue
ListRows. 12
3. Create a label to the left of the combo box.
4, Set the following properties for the Label:
Name. MonthText
Caption For Which Month?
718Excel 2000 Programming Working with Forms and Controls
Working with the Frame Control
‘You can use a Frame control to group a set of controls either functionally or logically
within an area of a UserForm. When Option Button controls are placed within a
frame, they are related logically: setting the valve of one effects the values of the
others in the group. Option buttons in a frame are mutually exclusive meaning that
when one is set to true the others will be set to false. When you want to display a
group of controls together because their content is related, a frame can be used to
group the controls functionally or conceptually. In that case, changing the value of
‘one control typically has no effect on the value of the others.
“The Frame control is represented in the toolbox by the fi icon.
Working with the Frame Control
Try It
1. Click {£8 Frame and draw a Frame control in the upper left-hand comer of the
frame.
2. Manually resize the frame so that it looks like the illustration above.
3. Set the following properties for the frame:
Name Period
Caption Period
4. Adda second frame to the right of the Period Frame.
5, Set the following properties to the frame:
Name SalesBy
Caption Sales By:
6. Resize the frame so it appears similar to the one in the illustration.
Ag
pes
Lo oeExcel 2000 Programming Working with Forms and Controls
Working with Option Button Controls
An Option button control displays a button that can be set to on or off. Option
buttons are typically presented within a group in which only one button may be
selected at a time. The Value property of the Option button control indicates the on
or off state of the button.
“The Option button control is represented in the toolbox by the [Ef icon,
Working with Option Button Controls
We will now add option buttons to the frame control. After this exercise, your form
Try It should look like the illustration below:
1. Chi OptionButton, move the mouse pointer within the Period Frame control
and click the left mouse button,
2. Create and place the remaining option buttons as shown in the illustration.
3. Set the names and captions for the option buttons as follows:
Name Caption
Today Today _|
Months | Month,
YTD. YTD.
‘OtherPeniod | Other Period
Salesperson | Salesperson
Model ‘Model
Classification | Classification
4. Drag one of the Frame controls to see how the option buttons move with the
frame. Drag the frame back into its original position when finished.
5. Save the project.
7-20MICROSOFT EXCEL
MACRO PROGRAMMING IN
VBA
PART IllExcel 2000 Programming Adding Functionality to Forms,
Functionality
Working with control appearance
Setting the tab order [
Populating a control
Adding code to controls
Launching forms from procedures
1Excel 2000 Programming Adding Functionality to Forms
Working with Control Appearance
‘The UserForm toolbar provides several tools that can be used to manipulate the
appearance of the controls on your form. The same functions provided by the
UserForm toolbar can also be accessed through the Format Menu. These functions
include grouping, aligning, sizing, and positioning controls.
To use many of the tools on the UserForm toolbar, itis necessary to frst select
multiple controls. To select multiple controls, click the first control then hold down
the (© Silt) key and click any additional controls. Controls will be aligned or sized
according to the first control selected. You will be able to tell which control was
selected first because its selection handles will be white.
The following is an illustration of a UserForm with multiple controls selected:
The following is an illustration of the UserForm toolbar followed by the options
ted with the Align, Center, and Make Same Size tools respectively:
Send to Back —Ungroup Center 200%
Bring to Fro Group. | | Make Same Size
a2Excel 2000 Programming
Adging Functionality to Forms
Working with Control Appearance
a
STEPS
ie
Display the UserForm toolbar, if necessary.
Select the desired controls.
To align the selected controls:
* Click the down arrow of the [EEG Aign toot; make the desired selection.
To group the selected controls:
+ Click EG Group on the Form Design toolbar.
‘To ungroup the selected controls:
+ Click $389 Ungroup on the Form Design toolbar.
‘To make controls the same height, width or size:
*+ Click the down arrow of the [gli Moke Same Size tool, make the desired
selection.
To center controls on the form:
“s Click the down arrow of the Hf Center tool, make the desired
selection.
®
‘The Center tool can be used to center controls within a frame.
‘You can select multiple controls by dragging a bounding box around them.
‘The Format menu contains options for vertical spacing not found on the
UserForm toolbar.
3Excel 2000 Programming Adding Functionality to Forms
Working with Control Appearance
The finished form should look like the one shown below:
Try It
Eom
1. Select the Today Option button in the Period Frame.
2. Hold down and select the remaining option buttons in the Frame.
3. Open the Format Menu, select Align and choose E¥ Lefis.
4. Open the Format Menu, select Vertical Spacing and choose [EB Remove.
5. Open the Format Menu and select Size to Fit.
6. Repeat this process with the Sales By frame.
7. Select the Period frame.
8. Hold down (Sill) and select the Sales By: frame.
9. Open the Format Menu, select Align and choose i Tops.
10. Right align the Start Date and Finish Date labels.
11. Select the Start Date label and its corresponding text box.
12. Open the Format menu, select Horizontal Spacing and choose {28 Remove.
13. Repeat this process on the Finish Date label and text box and for the
WhichMonth combo box and its label.
14. Left Align the Display and Cancel command buttons.Excel 2000 Programming Adding Functionality to Forms
Setting the Tab Order
The tab order is the order in which pressing the tab key moves the focus from control
to control on the UserForm. While you are building the form, the tab order is
determined by the order in which you place the controls on the form. If the controls
are subsequently rearranged, you may need to manually reset the tab order.
STEPS
‘The following is an illustration of the Tab Order dialog box:
Ler
Setting the Tab Order
View the desired form into the UserForm window.
Open the View menu.
Choose Tab Order.
Select the desired control from the list.
‘To move the control up in the list:
© Click Move Up.
To move the control down in the list:
+ Click Move Down,
‘You can select multiple controls from the list in the Tab Order dialog box
before moving them up or down, To do so, click the first item to be moved,
hold down (Gui) and click additional items.
Labels, although listed in the Tab Order dialog box, are not included in the
tab order,
‘You can also display the Tab Order dialog box by right-clicking a blank
portion of the form and selecting Tab Order from the shortcut menu.
e5Excel 2000 Programming
Try It
Setting the Tab Order
1. Select the Run Reports form,
2. Press (FS).
3. Tab through the form.
4. Click 8 Close on the form.
5. Open the View menu in the VB Editor and select Tab Order.
6. Select Begindate and click Move Up twice.
7. Select Display, hold down (Gi and select WhichMonth,
8. Click Move Down twice.
9. Click OK.
10. Select the Begindate text box and change its Enabled property to True.
11, Change the Enabled property of the Finishdate text box to True.
12. Run the form.
13, Tab through the form to see how tab order has been affected.
14, Click 8 Close on the form.
15. Retum the Enabled property of the text boxes to False.Excel 2000 Programming Adding Functionality to Forms
Populating a Control i
A List box or a Combo box control that you place on your form is not functional until
you add the data that will appear in the list. This is accomplished by putting code in
the sub procedure that is associated with the Initialize event of the form. ‘The code
placed in the sub procedure will execute when the event is triggered. The Initialize 1;
event is triggered when the UserForm is loaded. The Additem method of the List or |
‘Combo box control is used to specify the text that appears in the list. Since you will |
typically be adding a number of items to the same control, using a With statement }
will make coding easier. |
Below is an example of calling the Additem method: {
Choices.Additem “Red”
a7 alExcel 2000 Programming ‘Adding Functionality to Forms
Populating a Control
1. Right-click the Run Reports form and select View Code.
2. Select UserForm from the Object drop-down list, if necessary.
3. Select Initialize from the Procedure drop-down list,
4. Inthe UserForm Initialize sub procedure enter the following code:
‘With WhichMonth,
Additem "Jan"
-Additem "Feb"
-Additem "Mar
-Additem "Apr
-Addltem “May”
-Additem "Jun"
Additem “Jul”
-Additem "Aug"
Additem “Sep”
Additem "Oct"
‘Additem "Nov"
Additem "Dec"
End with
5. Close the Code window.
6. Select the RunReports form and press (F5)
7. Test the combo box.
8 Close the form
9. Set the Text property of the WhichMonth combo box to Jan. :
10. Run the form again and notice the default text in the combo box.
11. Close the form,
12. Save the workbook.Excel 2000 Programming Adding Functionality to Forms
Adding Code to Controls
Forms are event driven, the event that usually creates action is a button click. To
make forms do something we nced to write code for the events that we want to
monitor. The layout of the form will dictate what events need to have special
handlers attached to them.
In the case of our form, we want to monitor when the Display and Cancel buttons are
clicked as well as make available certain form options only when specific options are
selected. Specifically, only when Other period is selected in the Period Frame do we
‘want to activate the Start Date and Finish Date text boxes. When the Month period
is selected, we want to unhide the WhichMonth combo box and its label.
‘When the Cancel button is clicked, the form will simply unload, in other words it will
close. The Display button however has a more difficult task to accomplish. It must
evaluate both frames to determine which options were selected and then know which
if any of the other controls on the form to look to for information. ‘The event
handlers for controls are handled the same as other events you have already coded.
While the form is in design mode, double click on the form or a specific control and
the code for the event handlers will appear.
Adding Code to Controls
STEPS
1. Chick 2] ve Eto.
2. Double-click the desired form in the Project window.
3. To display the Code window for the form perform one of the following:
© Right-click the form and select View Code.
© Double-click on the form ora specific control.
4, Select the desired object from the Object drop-down list, if necessary.
5. Select the desired Procedure from the Procedure drop-down list, if necessary.
6. Enter the code for the event.
7. To return to the form select one of the following methods:
* Double-click the form in the Project window,
+ Click B8 Close,
+ Right-click in'the code window and select Hide.Excel 2000 Programming Adding Functionality to Forms
exe)
Try It
Adding Code to Controls
In this exercise we will create the event handlers for the Run Reports form.
1. Add the following lines of code to the UserForm _Initialize event sub procedure:
2. Add the following code to the Months Change event sub procedure. It hides or
‘shows the WhichMonth Combo box and its label when the Month option is
selected:
Private Sub Months_Change()
Hf Months. Value = True Then
WhichMonth. Visible = True
MonthText Visible = True
Else
WhichMonth. Visible = False
MonthText Visible = False
End If
End Sub
3. Create an event handler that will enable the Start Date and Finish Date text boxes
when the Other Period option is selected. (The finished code is on the last page
of the exercise.)
4. Enter the following line of code for the Cancel Click event. Me is a specific
reference to the active form. Me cannot be used with any other object.
Private Sub cancel_Click()
Unload Me
End Sub
continued on next page
ho nntinueed on next page
e10Excel 2000 Programming Adding Functionality to Forms :
Adding Code to Controls, continued
5. Add the following code to the Display Click event. This code evaluates which
option in each of the frames was selected by looping through each item in each
collection and determining which has the value property set to True (ie. which is
selected) and then placing what is contained in the caption property of those
option buttons into variables. We will use those variables in the next chapter to
control what report is generated. Place the Public variables in the General |
Declarations area.
‘Option Explicit |
Public SortBy As String
Public WhatPeriod As String
Private Sub Display_ClickQ
Dim DateRange As Control
Dim Group As Controt
For Each DateRange In Period.Controls j
Mf DateRange. Value = True Then }
‘WhatPeriod = DateRange. Caption
End If
Next DateRange
For Each Group In SalesBy.Controts
Group. Value = True Then
SostBy = Group.Caption
End If
Next Group
End Sub
6. Run the form.
7. ‘Tryto select the Start and Finish Date text boxes. :
8. Select the Other Period Option.
9. Select the Start and Finish Date text boxes,
10. Select the Month option.
continued on next page
aExcel 2000 Programming Adding Functionality to Forms
Adding Code to Controls, continued
11. Select a month from the combo box drop-down list.
12, Select Model in the Sales By frame.
13. Click Display.
14. Click Cancel.
‘The following code should appear in the userform initialize event sub procedure:
BeginDate.Enabled = False
FinishDate.Enabled = Fatse
The following code should appear in the OtherPeriod_change sub procedure.
Private Sub OtherPeriod_ChangeQ
Mf OtherPeriod. Value = True Then *
BeginDate.Enabled
FinishDate Enabled
Else
BeginDate.Enabled
FinishDate.Enabled
End If
End Sub
e12Excel 2000 Programming Adding Functionality to Forms
Launching Forms from Procedures
Try It
To launch a form from a procedure use the Show method. By creating a procedure
that launches a form, it allows the form to be launched on events like the opening of a
workbook or if a cell value falls below a certain level. It also allows forms to be
Jaunched from a toolbar or menu selection,
Following is the syntax for a line of code that launches a form:
FormName.Show
RunReports. Show
Launching Forms from Procedures
1, Create the following procedure in a Module in Fiscal Year Sales:
Sub LaunchReportsg,
RunReports. Show
End Sub
2. Run LaunchReports
ick Cancel,
4, Save the workbook.
5. Close the VB Explorer.
a3Excel 2000 Programming Using PivotTables
Understanding PivotTables
Creating PivotT ables
PivoiTable arguments
Adding fields to PivotTables
oFExcel 2000 Programming Using PivolTables
Understanding PivotTables
A PivotTable is a table in a worksheet that can be used to summarize data from a i
worksheet or an external source such as a database application, When creating a
PivotTable, you can select the data to analyze and the method to be used to |
summarize the data. After creating the PivotTable, you can rearrange the column and
row headings to display different views of the data. j
‘The only way to create a table is by using the PivotTable wizard. The wizard i
isplays a series of dialog boxes that request the type and location of the data; the
‘names of the rows, columns, page, and data fields; and where to place the completed
table. VBA is capable of controlling the PivotTable Wizard.
‘Below is an illustration of a PivotTable:
Page Feld 7 T Fe
{ = i
[Green |Red__|Silver “White {Yellow [Grand Total
Row Fie’ ——} ae | | 10] Row Grand
16,21], 10! ST T05] Total
72| | 91! 96/42 501
[Grand Total [94] [102/125 eo 616]
Column Grand Data Feta
The following is the PivotTable’s hierarchy:
|
|
[Proabes Pratabe) y
Lprairaa PioireaT: i
{ UPivotttems (Pivotliem) i
92Excel 2000 Programming Using PivotTables
Creating PivotTables
Wizards make the creation of PivotTables quite easy for the end user. By following
a series of prompts, the wizard is able to take over and actually create the PivotTable
for you. You can also write sub procedures that will call the PivotTable wizard, You
must include in your code the information that the wizard needs to create the
PivotTable,
Creating PivotTables
1. Open the Data menu,
2. Select PivorTable and PivotChart Report.
3. Select the data source type.
4. Select the type of report to create.
5. Click Next,
6. Select the source data
7. Click Next
8. Select the destination of the PivotTable.
9. Click Finish,
10. Drag the field butions to the desired page, row, column, and data fields
@ To delete a PivotTable from a worksheet: select the PivotTable; open the
Edit menu; select Clear; and choose Ail
a3Excel 2000 Programming Using PivotTables
cm
Try It
Creating PivotTables
This exercise will introduce the PivotTable. As you go through the PivotTable
Wizard make yourself aware of the information that it is requested.
1. Open the Data Menu and select PivorTable and PivotChart Report.
2. Close the Office Assistant, if necessary.
3. Click Next.
4. Select the data on the sheet. Include the headings, but not the totals.
5. Click Next.
6. Click Layout.
7. Drag the following headings from the right of the wizard window onto the
diagram, Use the illustration below as a guide. Note: Dragging Selling Price
into the Data area creates Sum of Selling Price.
8. Click Next
9. Select New Worksheet, if necessary.
10. Click Finish,
11. Delete the worksheet created by this exercise.
=
4
FoeExcel 2000 Programming Using PivotTables
PivotTable Arguments
A PivotTable can be controlled programmatically as well as with the wizard. While
the Macro Recorder can give you clues as to how to create a call to the PivotTable
‘Wizard, it is useful to understand the possible arguments for the wizard and when to
use them,
Below are the arguments for SourceType and SourceData relative to where the data
to be retrieved resides:
Source is SourceType SourceData
an Excel list or database —_xJDatabase arrange
an external datasource —_xlExternal an array that contains a
connect string and a SQL.
statement
Multiple consotidation _xIConsolidation an array of ranges
ranges
Another PivotTable or xIPivotTable an existing PivotTable name
PivotChart
‘The following are the other arguments used in PivotTable construction, all are
optional: :
TableDestination ‘Where the table will be Active cell
created
TableName A name by which the PivotTable with a
PivorTable can be referenced. suffix
RowGrand Displays the row totals ifset_ True q |
tote. |
i
ColumnGrand Displays the column totals if True |
set to true, '
SaveData Saves the created PivotTable True |
‘with the workbook if set to |
true i
HasAutoFormat Reformats the PivotTable True
when it changes if itis set to
true.Excel 2000 Programming
PivotTable Arguments, continued:
Reserved
Background Query
Optimize Cache
PageFieldOrder
PageFieldWrapCount
ReadData
Connection
Creates a pagefield
automatically for
consolidation PivoiTables
only when it is set to true.
Reserved for future use,
Leave this blank.
Creates a PivotTable in the
background if set to tue. If
false, the user must wait while
the PivotTable is constructed.
Optimizes the PivotTable
when set to truc. Useful for
very large amounts of data.
Determines the order of the
Pagefields, xIDownThenOver
runs the PageFields vertically.
xlOverThenDown runs the
PageFields horizontally.
Defines the number of
Pagefields before a new row
or column starts, based on the
PageFieldOrder. Zero
Prevents wrapping, any other
‘value determines the break
point,
Reads data into the
PivotTable cache (a holding
place for the PivotFable)
immediately if true. If false,
the data is not read until it is
needed
Used to specify a ODBC data
source (extemal data source),
@ URL data source, or a file
which contains a query.
Using PivotTables
na
True
False
xIDownThenOver
Zero
True
MaExcel 2000 Programming Using PivotTables
PivotTable Arguments
1. Enter the following sub procedure in a module in the Fiscal Year Sales
workbook. It runs the PivotTable Wizard, capturing the data in the current
worksheet and thea placing a PivotTable in a worksheet called Reports. For now
the PivotTable will contain no data because we haven’t assigned the row,
column, or data fields. Place Oprion Explicit in the General Declarations area.
‘Option Explicit
‘Sub MakePivotQ,
Dim DataRange As Range
Dim Destination As Range
Dim Pivotinfo As PivotTable
Set Destination = Worksheets( Reports"). Range("A1")
Set DataRange = Range("A1", Range(“s1").End(xIDown))
ActiveSheet PivolTableWizard _
SourceType:=xDatabase, SourceData:=DataRange, _
‘TableDestination: “Pivotinio”
End Sub
2. Create a new worksheet in the workbook named Reports.
3. Select any sheet that contains data.
4. Run the MakePivot sub procedure.
5. Save the workbook.Excel 2000 Programming Using PivotTables
Adding Fields to PivotTables
Row, column, page, and data fields are added to a PivotTable by using PivotFields,
PivotFields are a collection of the column data that exist in the SourceData. In the
previous example the PivotFields were: Vin Number, Year, Make, Model,
Classification, Color, Dealer Cost, MSRP, Selling Price, and Salesperson. Each
PivotFicld gets its name from the column header. PivotFields can be used as row,
column, page, or data fields at your discretion. |
‘The following are the possible PivotTable destinations for PivotFields:
Destination ‘Constant
Row Field xlRowField :
Column Field xiColumaField
Page Field xiPageField . 2
Data Field xiDataField
To Hide a field xlHidden ]
The syntax for adding a PivotFicld to a PivotTable follows: |
tTables(Name), PivotFields(Name).Orientati
PivotTables("Pivottnfo") .PivotFields “Make’).Orientation = xIRowField
= Destination
Indexing PivotFields
Since a PivotField is a collection, you can reference individual fields by indexing
them. ‘The syntax for Indexing PivotFields follows:
Worksheets(Name).PivotTables(Name). PivotFields(field name)
Worksheets(“Reports’).PivotTables(‘Pivotinfo’). PivotFields(Model’) 2
Indexing Pivotitems
Included in the PivotFields collection is the collection of all of the individual items
contained in the PivotField. This collection is called Pivotltems. As a collection the
Pivotltems can be indexed as well. The syntax for indexing a Pivotltem follows:
Pes
PivotTables(Name).PivotFields(field name).Pivotitems(item name)
PivotTables(“Pivotinfo").PivotFields("Model"), Pivotltems("Blazer’)Excel 2000 Programming Using PivotTables
Try It
Adding Fields to PivotTables
In the following exercise we are going to create a sub procedure that fills the
PivotTable with PivotFields named after the following public variables: PageName,
RowName, ColumnName, and DataName. These variables will be filled based on
the selections made on the userform:
PivotSelect is a method of the PivotTable object that is used to select PivotFields. In
the following code, PivotSelect is used to select the DataField so that it can be
formatted as currency.
1. Enter the following sub procedure into the same module in the FISCAL YEAR
SALES as MakePivot. Add the Public variables to the General Declarations area
of the code window.
Public PageName As String
Public RowName As String
Public ColumnName As String
Public DataName As String
‘Sub SetPivot)
Dim Table As PivotTable
Set Table = Worksheets("Reports’).PivotTables(‘PivotInfo")
‘With Table :
PivotFields(PageName), Orientation = xiPageField
-PivolFields(RowName).Orientation = xRowField
-PivotFields(ColumnName). Orientation = xIColumnField
-PivolFields(DataName) Orientation = xIDataField
End With
Table.PivotSelect ™, xIDataOnly
‘Selection. NumberFormat =
Range("Et").Select
End Sub
2. Until the userform is run, the variables will contain no values. For sake of
testing, temporarily assign values to the variables using the Immediate window.
Enter the following code in the Immediate window.
PageName = "Year"
RowName = "Make"
‘ColumnName = “Salesperson”
DataName = "Selling Price”
3. Run SetPivot.
4, Delete the Reports worksheet and save the workbook.
99Excel 2000 Programming
Controlling Forms
! ia
|
; ; Controlling PivofT.ables from a form
' Controlling a form from a custom toolbar '
7
4
10-4Excel 2000 Programming Controlling Forms
Controlling PivotTables from a Form
A form’s functionality comes from its ability to call procedures that create the
outcomes desired. Once a form is created and has code that evaluates what selections
the user has selected, code needs to be created that then distributes those responses to
the correct procedures.
So far we have created a UserForm named Run Reports that will allow users to create
custom reports. But it does not do anything yet. In this section we will add code to
make it create the reports we want.
In the Run Reports form we ask the user to enter what period they want a sales report
for (Today, Month, Y.T.D., or Other Period) and then how to sort that report (by
salesperson, model, or classification). We have alteady created procedures to
determine which options were selected in the form and have attached them to the
click of the Display button. We also have procedures that create and fill a PivotTable
(which is how we will display the report). Now we need to create procedures that
pass the correct information to the PivotTable.
10-2Excel 2000 Programming Controlling Forms
Try It
Controlling PivotTables from a Form
Depending on what period is selected we need to gather different information from
the Fiscal Year Sales workbook. Since the worksheets are named by dates, and dates.
can handle arithmetic operators (i.e. you can add 1 to the current date and get
tomorrow's date) we can create a procedure that is given start and finish dates and
then loops from one to the other. While looping through the sheets, a function will
grab the data from the sheet and place it ina temporary worksheet. Once the data is
Bathered it can be used to create a PivotTable.
L. Enter the following code in the Run Reports UserForm Code window; place the
Public variable in the General Declaration area,
‘The workbook being used is called Fiscal Year Sales; the StartDate for the
“Y.T. D.” case is the earliest date in the workbook. This represents the
beginning of the Fiscal Year, this date changes depending on when this course is
run and how many sheets are placed in the Fiscal Year Sales workbook. If you
‘would like to use January 1* as the start date; substitute StartDate =
"1/1/" & Year (Date) for the existing line of code below. Ifa worksheet
for Jan 1 does not exist, this will result in an error.
Public ThisMonth as String
Sub ConsolidationDates0,
Select Case WhatPeriod
‘Case “Today”
‘StanDate = Date
EndDate = Date
‘Case “Month”
‘ThisMonth = WhichMonth
Case "Y. T.D.”
StartDate = #00/00/00# ‘Enter the eartiest date in the Fiscal Year __
Sales workbook between the pound signs
EndDate = Date
Case "Other Period”
StartDate = BeginDate
EndDate = FinishDate
End Selec
End Sub
continued on next page
703
Po alExcel 2000 Programming Controlling Forms
Controlling PivotTables from a Form, continued
2, Now we need to create a procedure that handles the Sort By: frame’s options.
Depending on how the user wants to group the report, we need to assign different
PivotFields to the MakePivot procedure. In the form we created a variable
‘SortBy which contains the caption of the active option button in the Sort By:
frame. We need to create a procedure that assigns different PivotFields based on
the value of SortBy. The beginning of that procedure follows. Enter this code
into the Run Reports UserForm Code window:
Sub SonByGroupso,
Select Case SontBy
Case "Satesperson”
PageName = "Salesperson"
RowName = "Year"
ColumnName = "Make"
DataName = "Selling Price”
End Select
End Sub
3. Finish the procedure by adding cases for Model and Classification. For those
‘eases the variables should be the following: (If you need help, the completed
code is at the end of the exercise.)
Variable Model, Classification
PageName Model Classification
RowName Year Make
ColumnName Color Year
DataName Color Selling Price
continued on next page
10-4Excel 2000 Programming Controlling Forms
Controlling PivotTables from a Form, continued
4, Move the cursor to the end of'a module in the FISCAL YEAR SALES.
workbook.
5. Open the Insest menu in the VB Editor and select File.
6. Navigate to the student data directory and select the text file, CONSOLIDATE.
7. Click Open.
8. Move the Public variables of the newly inserted code to the General Declaration
area of the module. The inserted code contains procedures named Consolidate,
FinishReport, and GrabCells.
+ Consolidate is a sub procedure that creates a temporary worksheet named
Reports and then loops from the begin date to the end date of sheets in the
FISCAL YEAR SALES workbook. At each sheet it calls a function called
GrabCells. For the Today period, it only grabs one sheet. For the Month
period each sheet is looped through, if the month name is contained in the
worksheet name its contents are “grabbed”. The Month method will not
work correctly if the workbook contains data for more than 1 year.
‘+ GrabCells is a function that is passed a variable that tells it from which cell to
begin to grab ceils. The first time it runs it begins at row I to grab the
column headers (which the PivotTable needs to run) every subsequent time
through it starts at row 2 so the headings are not grabbed again. The data is
then added to the Reports worksheet.
+ FinishReport is a sub procedure that moves the collected data into a
workbook called Reports, deletes the temporary worksheet in FISCAL
‘YEAR SALES, and creates a PivotTable in REPORTS.
9, The 3" Tine of the FinishReport sub procedure opens a workbook called Reports
in the directory C:\Data. If the student data directory is different than C:\Data,
change the code so that it navigates to the correct folder.
10. Add the following code before the end sub line in the Display_Click event in the~
Run Reports form:
RunReports Hide
SortByGroups
ConsolidationDates.
Consolidate ThisMonth, WhatPeriod
FinishRepont
Unload Me
continued on next page
10-5Excel 2000 Programming Controlling Forms
Controlling PivotTables from a Form, continued
U1. The SetPivot sub procedure formats the DataField as currency. This is not
acceptable when the Sort By: option is Model because its DataField is a count of
inventory, not a dollar figure. Add the following lines of code to create
conditional formatting based on the value of the SortBy variable:
Sub setPivot
Dim Table As PivotTable
Set Table = Worksheets Reports") PivotTables(*PivotInfo")
With Table
PivotFields(PageName). Orientation = xiPageField
PivotFields(RowName). Orientation = xiRowField
PivotFiekis(CotumnName).Orientation = xiColumnField
PivotFields(DataName).Orientation = xDataField
End With
Table PivotSelect ™, xiDataOnly
If SonlBy <> "Model" Then
‘Selection. numberformat
End if
Range("E1"). Select
End Sub
12. Since the SortBy variable is created in the form; it will contain no value in the
module. ‘So the variable must be passed from the form to the SctPivot procedure.
But SetPivot is not called from the form, itis called from FinishReport. In this
case it is necessary to pass the SortBy variable to FinishReport and then pass it to
SetPivot. Make the following changes to the code:
* Change the sub SetPivot() line to read SetPivot(SonBy)
* Change the sub FinishReport line to read sub FinishReport(SortBy)
+ Inthe Display_click event in the form, change the call to the FinishReport to
read FinishReport SortBy :
13. In the MakePivot sub procedure, rewrite the following line to appear as it does
below it. This is because it is not necessary to grab the Vin Number field for the
PivotTable, so the consolidated data only fills columns A:1.
‘Set DataRange
Set DataRange
range(’A1”. range("J1"), End(xiDown))
range("A1", range("11"},.End(xIDown))
continued on next page
106Excel 2000 Programming
Controting Forms
Controlling PivotTables from a Form, continued
14, Save the workbook.
15. Run the form.
16. Select Month for the period.
17. Select Jast month from the combo box.
18, Select Salesperson from the Sales By: Frame.
19. Click Display.
20. Click OK. (This deletes the temporary worksheet created in Fiscal Year Sales.)
21. Close the Reports workbook (saving before closing is optional).
22, Run the form a few more times checking that the form is functioning correctly.
Remember to close the Reports workbook after each running of the form.
Sub SonByGroups
Select Case SoniBy
Case "Salesperson"
PageName = “Salesperson”
RowName = “Year
ColumnName ="Make”
DataName = "Selling Price*
Case “Model”
‘ColumnName = "Color™
DataNarie = "Color
Case “Classification”
PageName = “Classification”
| RowName = "Make
ColumnName = "Year"
| DataName = "Selling Price”
|
End Select
End Sub
10-7Excel 2000 Programming Controlling Forms.
Controlling a Form from a Custom Toolbar
Procedures can be executed from the Macro. dialog box and from within other
Procedures. They can also be executed from toolbars and menus. By modifying
existing toolbars and menus to contain references to procedures, procedures can be
Jaunched directly from the desktop.
Aside from the built-in toolbars available within Excel, you can also create custom
toolbars and then attach calls to macros to those toolbars. By adding code to the open
and close events of a workbook you can create toolbars that only appear while certain
workbooks are open.
‘The following is an illustration of the Customize dialog box used to create custom
toolbars:
10-8Excel 2000 Programming Controlling Forms
Controlling a Form from a Custom Toolbar
Open the Customize dialog box using one of the following methods:
‘+ Open the Tools menu and select Custonrize,
© Right-click in the toolbars area of the Excel window and select
Customize.
Click the Toolbars tab.
Click New.
Enter a name for the new toolbar and click OK.
Click the Commands tab.
‘Select Macros fiom the Categories list.
Drag the Cusiom Button icon onto the new Toolbar.
Click Modify Selection,
Click Assign Macro.
. Select a Macro name from the dialog box and click OK.
Click Close,
In VBA, menus and toolbars are collectively referred to as Command Bars
and can be manipulated programmatically using the CommandBars
collection and the CommandBar object.
While the Customize dialog box is displayed, you can drag toolbar icons to ,
any other toolbar, menu, or sub menu,
Macros on a toolbar work even ifthe workbook they exist on is closed
To remove a toolbar, open the Tools menu and select Cusiomize. Click the
Toolbars tab, select the toolbar to be deleted, and click Delete
‘To remove a created menu item, while the Customize dialog box is opened
drag the menu option off of the menu bar and release the mouse button,
Since a menu is a customized toolbar, the process of adding macros to a
menu is just about the same. Instead of selecting New from the Toolbars tab,
select New Menu from the Commands tab and then follow the remaining
steps in the Controlling a Form from a Custom Toolbar procedure.
109Excel 2000 Programming Controlling Forms
Try It
Controlling a Form from a Custom Toolbar
Open the Tools menu in Excel and select Customize.
2. Click the Toolbars tab.
3. Click New.
4. Type Reports in the Toolbar Name text box.
5. Click OK,
6. Click the Commands tab and select Macros from the categories list.
7. Drag the Custom Button icon to the new toolbar.
8. Click Modify Selection,
9. Type Report Button forthe button name.
10. Select Change Button Image.
11, Select [EBB from the selections.
12. Select Modify Selection.
13. Select Assign Macro.
14, Select Launch Reports from the dialog box.
15. Click OK.
16. Click Close.
17. Place the toolbar where you like.
19. Click Cancel
continued on next page
10-10Excet 2000 Programming Controlling Forms
Controlling a Form from a Custom Toolbar, continued
20. Add the following line of code to the workbook’s open Event:
Application. CommandBars(Reports?) Visible
21. Add the following line of cade to the workbook’s Before_close Event: 4
Application. CommandBars(Reports’). Visible
22. Save and close the workbook. {
23. Verify that the Reports toolbar is tured off.
24. Open the FISCAL YEAR SALES workbook.
25. Click OK.
26. Verify that the Reports toolbar is on.
27. Close the workbook.
,
10-19Excel 2000 Programming Understanding Debugging
tanding Debugging
Understanding errors
Debugging code
Debugging tools
Using the Locals window
Using the Watch window
Using Breakpoints
TtExcel 2000 Programming Understanding Debugging
Understanding Errors
Throughout program development, problems with the project will occur.’ Incorrect
control logic, improper fianction usage, data type mismatches, variable naming or
scoping problems, as well as overflow and division by zero errors are quite common
within the program environment.
Errors are often called bugs. The process of removing bugs is called debugging.
There are 4 groups of errors that can occur in a project. VBA has tools that assist the
programmer in dealing with many of them. Following is an explanation of the 4
error types,
Syntax Errors.
‘These errors generally occur as the result of an error of omission. As you move off
‘of a line of code in the code window the syntax of the line is checked, provided the
Auto Syntax Check is tumed on. If'a syntax error is Jocated in the line of code, the
centire line will turn red by default to indicate that the line needs to be changed.
Common Syntax errors are not completing an expression or not entering all required
arguments,
Compiler Errors
‘The compiler is what actually runs procedures. Before the compiler executes code it
checks that all variables are declared (if Option Explicit or Force Variable
Declaration is selected) and that objects have references to correct methods,
propertics, and events. The compiler also checks if code clements that appear in
pairs have both arguments present. In other words, each If has a corresponding End
If, each Do has a Loop associated with it, etc.
‘When the Compiler locates an error, it generally displays a message box describing
the error.
Logic Errors
‘These are errors that the compiler doesn’t recognize as errors. Logic errors create
unexpected outcomes when a procedure is executed. For example, if you want to
place the value of the cell to the right of the active cell into a variable but you
inadvertently use the expression Range(ActiveRange).Offset(.1) to do so, an error
will not occur unless the active cell is in row 65,536 (which is the last row in any
worksheet) or the data in the selected cell doesn’t match the type expected by the
variable. Barring these instances, the code will execute, but the variable will not
contain the expected value.
saa OT OT saExcel 2000 Programming Understanding Debugging
Understanding Errors, continued:
Run-Time Errors
A run-time error is one that only occurs when certain conditions are met, A
Procedure may work 10 consecutive times, but on the 11” an error may occur.
Recognizing what condition was different on the 1” pass through the procedure is
the key to understanding what caused the error.
Ifyou recall, we encountered a run-time error earlier when we attempted to add totals
to sheets in Fiscal Year Sales that contained no data. In that instance'we created a
‘conditional statement that would only allow the AddTotals procedure to run under a
certain condition.
When a run-time error occurs, a message box generally appears that defines the error.
Often the error will halt the execution of the code. ‘This can create large problems
because a procedure will only partially be executed. Once cxecution is halted, the
code may need to be changed to fix the problem, which will likely reset the project.
Not only does this present problems for the programmer, but for anyone else who.
uses the code who encounters a run-tinie error it is highly unlikely that the error can
be easily fixed
1Excel 2000 Programming
Understanding Debugging
Debugging Code
Unfortunately, there is no science to debugging errors. Finding errors is often the
result of detective work, patience, and some lucky guessing, What follows arc a few
suggestions that you can usc to help you minimize difficulty in locating errors in your
code.
Add as many comments to your code as possible. This is particularly
important if someone else will be looking at your code. Well written
‘comment lines explain what a line of code or procedure is supposed to do.
‘Add prefixes to variable names that describe the object or the DataType of
the value to be contained in the variable. For example, for objects like
buttons, begin variable names with the prefix bar. Ifa variable contains
integer data begin the variable name with int.
‘Any time you use division that contains a variable in the denominator, figure
‘out under what conditions the denominator can be zero. For example, a
declared numeric variable contains the value zero until it has another value
assigned to it.
Force variable declarations. This eliminates the possibility of misspelling a
variable name when you use it multiple times,
Keep each procedure as short as possible, giving it one or two specific tasks
to carry out. Give piocedures names that clearly describe what they do.
Test procedures with large data sets that represent all of the possible
permutations of reasonable and unreasonable data. In short, try to make the
Procedure fail before someone else tries for you.
ara
ReExcel 2000 Programming Understanding Debugging
Debugging Tools
VBA has quite a few tools that can help locate logical and run-time errors, While
none of them will solve errors, they will Iet you examine what the objects and
variables are doing during execution.
The following is an illustration of VBA’s Debug toolbar followed by an explanation
of each took:
Design Mode disables event driven procedures from executing.
-RusiContinue ‘ins code or resumes the nanning of code after a
break.
[Bj Break ‘stops the execution of code. Allows you to continue
execution fiorn the break point
[E Reset ‘stops code execution:
[BR] Toole Broakpoint a.user determined line of code that execution will
- ‘break at during execution.
B ‘Step:Into ‘executes next line of code each time (F8) is pressed.
[BQ step Over allows selected code to be stepped over during
execution.
Ey Sep out executes remaining code in the calling procedure
after a break.
[EX Locals Window displays the value of variables and properties during,
code execution, 7
[EJ immediate displays a window where individual lines of code can
Window be executed and querying of specific variables can
occur.
Walch Window displays a window to set breakpoints in code when
specified expressions are tre.
a
‘Quick Watch, Tetums the value of an expression.
i ia
Call Stack displays all procedures that have been called up to a
breakpoint in code execution.
15Excel 2000 Programming Understanding Debugging
Using the Locals Window
‘The Locals window displays the current values and data types for all variables in
procedures being executed during a step through of code. Ifa variable is a reference
to an object then the properties of the object can be viewed as well. This is a |
valuable tool for finding the conditions under which run-time errors occur.
Below is an illustration of the Locals Window: |
@ By pressing the and © before the modules and objects you can expand ‘
or collapse them to display more variables and properties. |
Using the Locals Window
1. Open the VB Editor. J
2. Choose the preferred method to display the Locals window: 5
* Open the View menw and select Locals window.
© Click {6 Locals Window fiom the Debug toolbar. [
"3. Step into the desired procedure.
11-6 LExcel 2000 Programming Understanding Debugging
ee
Try It
Using the Locals Window
In the exercises in this chapter we are going to use a workbook called Critical
Inventory. All we know about Critical Inventory is that it is supposed to indicate
when inventory falls below a certain level and that currently it is not working,
correctly. We are going to usc the Locals window to help us understand what the
Procedure does and gather an understanding of why it doesn’t work,
1. Open the workbook CRITICAL INVENTORY.
2. Rum the procedure Order.
3. When the procedure seems to stop working correctly press
4. Click Debug.
5. Read the comment associated with the loop statement.
6. Move the insertion point over the variable ModelName to display its current
value.
7. Click
8. Retum to Module J, if necessary.
9. Click [EY Locats Window.
10. Adjust the VB Editor and Locals windows so you can sce Columns A:C of the
worksheet. Closing the Project window may help.
11. Place the cursor in the Order sub procedure and press (Fi) .
12. Begin stepping into the procedure.
13. Expand the modulé and objects in the locals window as needed to view more
variables, ‘
14. After you have stepped enough times to understand how the Procedure works
click Hi Reset,
15. Close the Locals window.
—_—Excel 2000 Programming Understanding Debugging J
Using the Watch Window
‘The Watch window is the last of the VBA windows. The Watch window allows its
user to create an expression that is continually evaluated., When it becomes True the
window will break the code, In the last example we know that the condition of }
interest was when the model is named Corvette. By stepping through one line at a ;
time we would have gotten to that point in execution, but not until [F8) was pressed
too many times to count. The Watch window allows code to execute until a point of 7
interest in the code is reached and then allows you to Step Into the program from that
point.
Below is an illustration of the Watch window and the Add Watch dialog box, which.
is where the user sets up the Watch Expression:Excel 2000 Programming Understanding Debugging
a
STEPS
@
Using the Watch Window
To add a Watch Expression:
+ Open the VB Editor;
+ Open the Debug Menu;
Select Add Wate!
+ Enter the expression to watch;
Select the procedure the variable appears in from the Procedure drop-
down list;
Select the module that the procedure appears in from the Module drop-
down list;
‘+ Select the appropriate option from the Watch Type frame;
Click OK.
To edit a Watch Expression:
* Open the VB Editor;
+ Open the Debug menu;
Select Edit Watch;
+ Make necessary edits;
© Click OK.
To delete a Watch Expression:
+ Open the VB Editor,
* Open the Debug menu;
+ Select Edit Warch,
* Click Delete.
To edit an expression from the Watch window, select the expression and
make any necessary ‘changes.
You can also right-click in the Code window and sclect Add Watch to add a
watch expression,Excel 2000 Programming Understanding Debugging
T
Using the Watch Window
From the previous example, we know that a run-time error occurs when the model is
Try It a Corvette. In this example we will use the Watch window to create a break in the
code when the model is a Corvette and then we will step into the program from that
point.
1. Open the Debug menu and select Add Watch.
2. TypeModel = “Corvette” in the Expression window.
3. Select Order from the Procedure drop-down list. +
4. Select Module from the Module drop-down list y
5. Select Break When Value Is True from the Watch Type frame.
6. Click OK.
7. Rum the Order macro.
8. When the procedure breaks, press (Fé) repeatedly. The procedure is attempting
to find a match for the model name-with a name on the Critical Inventory sheet.
9. Once you realize what the problem is click {Zig Reset. |
10. On the Critical Inventory sheet, change the entry for “Corvete” to Corvette. 1
11. Open the Debug menu. |
12. Select Edit Watch.
13. Click Delete.
14, Close the Watch window. : S :
15, Run the Order procedure.
16, Save the workbook.
Oech
17-10Excel 2000 Programming Understanding Debugging
Using Breakpoints
A breakpoint creates a stopping point in the execution of code. This acts similarly to
the Run to Cursor feature in that they both create lines in code where execution is
halted, where they differ is in their permanence. The Run to Cursor feature executes
‘one time and must be called by the Run fo Cursor option in the Debug menu,
Multiple breakpoints can be set in code and they remain in place until they are
removed. This is of great value if you are testing code repeatedly. Breakpoints are
also activated from the Rurt command instead of having to use a special debugging.
feature,
‘The most important feature of the breakpoint is one can be set in a procedure other
than the parent procedure. The Run to Cursor option only works within the current
Procedure. Breakpoints can be set in sub procedures or functions that are called from
& parent procedure. In situations where variables or arguments are passed toa
Procedure it becomes essential to run the parent procedure before breaking the code.
When code is executed that contains a breakpoint, execution will pause at the
breakpoint and that linc is the next to be executed just as with the Step Into feature.
From the breakpoint you can either resume execution or you can step into the code
Below is an illustration of code contai
ing several breakpoints:
Cleacontents "Clears Inventory Table workaneer
texerivor. Creates tnpty Prsettabie
BetFivet “Tiiis pivoePielae :
TR TE
for Fach Hodel In Thispivot Fivoerieiae (hose Peon
NodeiNene = Rodel ‘ereateo a variable of type sting to ane
Finanocch ‘compares current nogel name an PivorTanle to
the table on the Critical Invencocy Sheet
there = nodelWane ¢ "few Grand total =
eS ea ar reeererTy
Essrisetteoreapenny
Coune = Activecell.Vatue
Te count < ceiticalVeiwe Then :
a
fennneerereacte ne prea
ActiveCell.oftset(, 1).Value = DesiredStock — Count “calcul
fee
detivecell.offsec{, 1).Value = 0 ‘Mo need to order, a
WatExcel 2000 Programming Understanding Debugging :
By default, breakpoints appear in red text. You can change the color of the ,
text in the VB Editor by opening the Tools memu, selecting Oprions, and
clicking the Editor Format tab. ‘Then select Breakpoint Yext from the Code j
Colors list and make changes as desired
Breakpoints can only be set on executable lines of code. They cannot be set
on variable declaration or comment lines |
Using Breakpoints
1. Toadd a breakpoint:
© Open the VB Editor;
+ Display the desired code in the Code window;
* Click in the margin to the left of the line of code where you want to set a
breakpoint,
2. Toremove a breakpoint:
© Open the VB Faditor; |
+ Display the code that contains the breakpoint in the Code window;
‘+ Click on the breakpoint indicator on the left margin.
WAZ 1Excel 2000 Programming Understanding Debugging
Try It
ee
Using Breakpoints
In this exercise we are going to use breakpoints to test the Order procedure again,
‘This time we want to check if the procedure is yielding the correct ordering
information. In this instance we are interested in two points: the first is when a
match is found for the model in the PivotTable with a modelname on the Critical
Inventory sheet. The second is when the order value is calculated.
1. Open the VB Editor, if necessary.
2. Click in the left margin of the code window at the following line of code in the
FindMatch procedure:
CriticalValue = ActiveCell.Offset(, 1).Value ‘value to the sight _
‘of the match is how many to warn at
3. Create another breakpoint in the Order procedure at the following line.
Hf Count <= Criticalvalue Then
4. Open the Locals window.
5. Run the Order procedure,
6. Expand Modulel in the Locals window, if necessary.
7. Press (FB) twice.
8. Press(F5).
9. Expand Module! again, if necessary, and resize the Locals window so that you
can view the value of the Count variable.
10. Press (F8) untit the End If line executes.
11. Press|
12. Repeat the process until you have scen both conditions of the If statement
execute.
13. Click i Reset
14. Remove the breakpoints.
15. Save and close the workbook.
1413