Programming MS Excel in Visual Basic (VBA) : Part 2-Branching & Looping, Message Boxes & Alerts
Programming MS Excel in Visual Basic (VBA) : Part 2-Branching & Looping, Message Boxes & Alerts
by
Abstract
This course is the second of a four-part series on computer programming in Excel Visual Basic
for Applications (VBA), tailored to practicing engineers. In this course the topics, conditional
statements, message boxes and alerts, and looping structures are presented. Several examples
relevant to engineering are used to illustrate and demonstrate the concepts and methods learned
in this class. Two mini-projects are used to demonstrate the programming concepts and methods
in situations encountered by practicing engineers.
Computer Programming in Visual Basic (VBA) – Part 1 is not required as a pre-requisite to this
course. It would however be helpful to understand the basic principles of computer programming
as well as the fundamentals of the Excel VBA language as presented in Part 1 of this series.
TABLE OF CONTENTS
Abstract ........................................................................................................................................... 2
List of Tables .................................................................................................................................. 4
List of Figures ................................................................................................................................. 5
1. CONDITIONAL STATEMENTS .............................................................................................. 6
1.1 Definition .............................................................................................................................. 6
1.2 If-Then-Else Statement ......................................................................................................... 6
1.3 Logical Operators.................................................................................................................. 7
1.4 Composite Conditional Expressions ..................................................................................... 7
1.5 Nested Conditional Statements ............................................................................................. 9
1.6 Select-Case Statement......................................................................................................... 10
2. MESSAGE BOXES AND ALERTS ........................................................................................ 15
2.1 Message Box ....................................................................................................................... 15
2.2 Simple Message Box........................................................................................................... 16
2.3 Message Box with Options ................................................................................................. 22
2.4 Manipulating Style Value ................................................................................................... 26
2.5 Third VBA Project .............................................................................................................. 29
3. LOOPING ................................................................................................................................. 62
3.1 For-Next Loop .................................................................................................................... 62
3.2 Nested Loops ...................................................................................................................... 64
3.3 Do-Loop .............................................................................................................................. 65
3.4 Exiting a Loop..................................................................................................................... 67
3.5 Fourth VBA Project ............................................................................................................ 67
4. CONCLUSION ......................................................................................................................... 94
REFERENCES ............................................................................................................................. 95
List of Tables
List of Figures
1. CONDITIONAL STATEMENTS
1.1 Definition
The most common conditional statement is the If –Then-Else statement. If the specified condition
is met, a block of code will be executed, else a different block of code will be executed. In VBA
the syntax is as follows
If condition Then
Run this code
Else
Run that code
End If
An alternate format allows the Else condition code to be placed on the same line as Else word, as
follows:
If condition Then
Run this code
Else: Run that code
End If
For more than two conditions, the ElseIf condition(s) is added as follows
If condition 1 Then
Run code 1
ElseIf condition 2 Then
Run code 2
ElseIf condition 3 Then
Run code 3
:
:
:
ElseIf condition (n-1) Then
Run code (n-1)
Else
Run code n
End If
As with the fundamental two-condition set up, the Else statement may be on the same line as the
relevant code but separated from the code by a colon. In all of the above cases the Else statement
is optional.
The condition in the condition statement is a logical expression where a logical operator (also
called a Boolean operator) is applied to compare, evaluate, or check that the inputs (called
operands) meet the specified condition and give a result of “TRUE”, based upon which the
relevant block of code will execute.
Conditional expressions may be combined using the “And” and/ or “Or” operators to form a
composite conditional expression.
For example, consider a bank account that has been overdrawn. If another charge comes in and
the bank pays it, the account goes further into the negative and is charged an overdraft penalty
for that transaction. However if a deposit comes in that partially clears the deficit, even though
the account is still in the negative, the account is not charged an overdraft fee for that transaction.
Therefore, using the negative sign for a charge transaction and positive sign for a deposit, the
overdraft penalty fee is applied as follows:
Else
End If
In each case, the If-ElseIf-Else-End syntax for each conditional statement must be complete on
its own regardless of whether it is nested or not. For instance, in the above example, if the End If
of the nested If statement was omitted, the syntax would be incorrect and a compiler error would
occur. A common format to keep track of this, as demonstrated in the above example, is by
typing the code such that the If-ElseIf-Else-End If for a specific If statement are aligned vertically
and that of any nested statements are offset laterally from the main statement in which they are
nested. This is called indenting the code.
The choice, relevance, or advantage of nesting versus composite conditions must be determined
by the programmer based on the specific objectives and requirements of the application.
This is an alternate method to the If –Then-Else. It is advantageous to use when there are too
many conditions and the If-Then-Else statement becomes cumbersome and difficult to follow and
keep track of. The syntax is as follows:
The Select-Case format may also have combined logical expressions, and may involve nesting.
Example 1:
Review the code for a grade calculator for an Engineering professor. A score of 95 and above is
+A, from 90 to 91.999 is -A, from 85 to 89.999 is +B, and so on, anything less than 60 is an F.
The professor enters the grade in a cell on the spreadsheet and presses the button which fires the
code that checks the score and assigns the grade and a comment, and displays them back on the
spreadsheet.
Declare variable
Conditional statement,
composite statements, used
(If-Then-Else) to assign
letter grade and comment
Example 2:
Alternately the Select-Case conditional statement may be used. In this example a simplified
grading system is used. 90 and above is A, 80 to 89.99 is B, 70 to 79.99 is C, 60 to 69.99 is D,
and anything else is F.
A message box acts like a dialog box where a user can interact with the computer. Message
boxes are used to alert or prompt the user. Message boxes are able to perform actions in response
to what the user selects. Message boxes can be incorporated into conditional statements.
The Prompt is the statement that will appear across the main body of the message box. The Style
Value relates to the buttons that will appear on the message box such “OK”, “Yes”, “No”, or
“Cancel”, as well as any symbols, such as a question mark, exclamation point (for a warning
message box for instance), informational sign etc. The Title is what appears in the title bar across
the top of the message box.
Title
Prompt
A simple message box will be created in this section. The message box will be activated by
clicking a push button on a spreadsheet.
From the Developer tab, select Design Mode. Applications can be built directly on a spreadsheet
once in Design Mode.
Click on Insert.
Select Command Button under ActiveX Controls.
Holding down the mouse, trace the shape and size of the command button on the spreadsheet.
Right click on the command button again, this time select View Code.
Drag the new command button to reposition and align it with the previous one.
Right click on the new command button.
Select Properties.
Double click on the Message Box with Options and type in the following code in its click
procedure:
Title
Prompt
Style Value
Answer “Yes”
Style Value
Alternate
conditional
statement setup
for message
box
Problem Statement:
Develop an application a city traffic engineer can use to determine whether it is justified to
install speed humps on a residential street. There have been complaints of speeding and cut-
through traffic. The applicable laws, rules, and industry guidelines are as follows:
For the speed humps to be approved, a) through e) must apply in addition to a combination of e)
and f) or e) and g).
The engineer will be using this tool on a laptop in the field. To facilitate the data entry in the
field, the engineer prefers to be able to select the applicable criteria from drop down menus
rather than typing in all the information. The engineer wants to have a click button which will
cause a text box to indicate that the speed humps are or approved or not approved. A pop up will
then inform the engineer that all commands have been executed to completion.
Solution:
Based on the criteria and the requirements for this tool, the form will have 7 combo boxes (drop
downs), and a text box to display the result. Add two more text boxes so the engineer can enter
his/ her name and date. Give the form a caption such as “Neighborhood Traffic Analyst” and add
a logo onto the form.
The inputs in the evaluation for speed humps will come predominantly from drop down menus
(combo boxes) as requested by the engineer. The form has been split into four sections using the
Frame control. All buttons pulled onto a Frame can be moved around as one block by clicking
and dragging on the Frame. The frames provide clarity by enhancing organization of the controls
and being visually appealing. The Caption property of a frame is used to change the wording on
the top of the frame.
On clicking the Run button the calculations will execute and a result indicating that speed humps
are approved or otherwise will appear in the Result text box in the Analysis frame. One frame
holds the company logo. This is an image control dragged onto and sized to fill the frame. By
selecting the blank image control and going to its property Picture, the programmer can navigate
to a picture on the computer and select it to be assigned to the image control. .
Image
Combo Boxes
The combo boxes are currently empty. To populate them, code has to be written to load a drop
down list of items. This can be done in a number of ways. One common approach is to add the
code to the event of opening or activating the main form. The syntax is
This code will be repeated for each item in the drop down list. The process will then be repeated
for each combo box on the form as follows:
Maintenance Responsibility:
Double click on the form to open the code window. The default event for the form is Click,
change it to Activate in the event menu, or in the code window, simply type over the “Click” to
replace it with “Activate”.
Select a drop down item to ensure it populates the box without any error messages.
This has been a success.
The process will be repeated for all the other combo boxes. Append the code to the Maintenance
Responsibility code in the UserForm Activate event.
Road Classification:
Number of Lanes:
Cut-Through Traffic:
This is the volume of traffic trips that do not originate on the street and do not have a location on
the street as the destination for the traffic trip. These are vehicles that are using this street as a
by-pass route to get to wherever they are going. In this model, cut-throughs will be expressed as
a percentage of the average daily traffic volume.
All combo boxes have the property Locked set to False. This means that the combo boxes are
not locked and that users can type in entries in addition to selecting from the drop down list if
they so choose.
At this stage all input data has been provided on the form for the calculation to proceed. Based
on the narrative of the problem, the following algorithm models the evaluation process.
START
Enter
Maintenance
Responsibility
No
‘City
?
Yes
Enter Road
Classification
No
Local
?
Yes
A B
A B
Enter Number
of lanes
No
>2
?
Yes
Enter Posted
Speed Limit
(PSL)
No
> 40
?
Yes
Enter Ave.
Daily Traffic
(veh per day)
No
> 500
?
Figure 1 (continued): Algorithm for
Third VBA Project
A B
A B
Yes
Enter: 85th
Percentile
Speed
No Enter % Cut-
>PSL+12 through
?
Yes
Yes No
>65%
?
STOP
The evaluation process will execute upon clicking the Run button. Therefore the Run button’s
click event shall contain all variables needed for the evaluation to proceed.
Declare variables for each input. Note that as code is typed the VBA Library provides tips and
pointers to guide the programmer.
Note that the programmer may choose any name of their choice for variables provided they meet
the variable naming rules and conventions discussed in Chapter 3. The final list of variable
declarations used in this application is as follows:
The next step is the assignment of values to the variables from the form. For example,
ComboBox1 contains the information that will be stored in the maintenance responsibility
variable; TextBox1 contains the average daily traffic, and so on. The variable assignments are
follows:
The speed humps will not be approved if the street is not under City maintenance responsibility.
It will not be approved if the posted speed limit exceeds 40 mph etc. These requirements or
conditions must be implemented using conditional statements with the appropriate logical
expressions. Note that the string variables must have their values wrapped in double quotation
marks whereas the numerical variables do not.
Note the use of a nested If statement in addition to the composite logical statements. Think of
other ways this can be accomplished.
Note the use of a line continuation at the end of the first line. This is used if the line of code
becomes excessively long. A line continuation is created in the following way
Hit the spacebar.
Type an underscore.
Hit Enter.
It may happen that a user may forget to enter information in a box where it is required. This may
cause the program to produce a run-time error. To prevent this, code must be added that will alert
the user that there is missing data in the process and will terminate the procedure, enabling the
user to go back, review, and make the necessary corrections.
Add an If statement that checks if is there are any controls (or variables) with null values, and if
so alert the user with a message box and prematurely exit the procedure. This block of code shall
be placed anywhere before the variable assignments.
Add a message box at the very end of the procedure alerting the user that the program has run to
completion.
A compile error is detected and highlighted. The traffic volume variable is being assigned the
value in Textbox4 which does not exist. This is a typo and needs to be changed to TextBox1.
Fill out the form in its entirety. Click the Run button to conduct the evaluation.
The test is a success. All requirements and features requested by the engineer have been
accomplished.
As seen, this tool opens upon activating it through the Excel program. It also opens with the
Excel program in the back ground. The client wants this tool to open automatically and as a
stand-alone, with no other program open in the background. To write the code for this, open code
window for this Excel workbook as follows:
Double click on ThisWorkbook in the Project Window.
Closes Excel
background
Therefore on clicking to open this Excel file, once it opens, the Excel background will become
invisible, and then the form will open.
Save and close out of Excel
If it ever becomes necessary to reactivate the Excel background for example to update some
codes, perform the following:
Save and close out of Excel.
Open the folder containing the file.
Hold down the Shift key
Double click on the file to open it
The full Excel view is opened.
The test is a success. This project has been completed to the satisfaction of the client.
3. LOOPING
In VBA this type of loop is used when it is pre-known how many times the loop will be repeated.
The syntax is
For loopvariable 1 To n
Next loopvariable
The loop variable (or loop counter variable) is an integer or long type. It will start at 1, and the
code will run. The Next will increment the loop variable to 2 and send it back to the For line
where it will be checked against the n value. If it is less than or equal to n the next iteration of the
code proceeds, if it is greater than n the loop has run to completion and the code will not be
repeated further. The cursor then moves to the line after the Next.
The loop variable call on the Next line is optional in VBA, and is by and large omitted or made a
comment. If the increment needed is to be in steps of 2 or more the code is as follows
Next
In this case the loop variable will jump from 1 to 1 + m, and so on, up to the value of n.
Next
Example:
In this example the main body of the loop is such that the value of the loop variable is displayed
in a cell on the spreadsheet in the column 1 (or A). The cell row designator is the loop variable i,
therefore each time i increments, the display location on the spreadsheet will jump to the next
row below, hence the results filling down the spreadsheet. Change the number of iterations to
10,000 and see what happens.
Example:
Fill cells A18 through E35 with a value which is calculated by addition of the cell’s row number
and its column number.
Loop to
fill rows
Nested Loop to
fill columns
3.3 Do-Loop
If the number of iterations needed is not known a piori, then the For-Next loop cannot be used.
In that case a Do-Loop structure will have to be used. In the Do-Loop, the programmer sets
conditions upon which the looping will terminate but will not know how much iteration will
actually run until termination occurs.
Code to be repeated
Loop
The termination condition is generally some logical expression. After each iteration, the
termination condition will be checked. If it has been met the loop will stop and the cursor moves
to the line after the “Loop” line, otherwise it will move to the next iteration of the code in the
main body of the loop.
The termination condition must be chosen carefully and studied closely otherwise the program
may fall into an infinite loop. An infinite loop is a loop that lacks a functioning exit routine . As a
result the loop repeats continuously until the operating system senses the issue and terminates the
program, or until some event, for instance having the program terminate automatically after a
certain duration or number of iterations, occurs. Infinite loops are capable of easily crashing
personal computers.
• Do...........Loop While
• Do until.............Loop
• Do............Loop until
Each style requires the termination statement be set up in a certain way that is consistent with the
logic of that style.
Example:
In this simplified example the loop variable is counter. Note that unlike the For-Next loop where
the program automatically increments the loop variable, in the Do-Loop, the loop variable must
be incremented “manually” by the programmer. However this makes the incrementing more
flexible than in the For-Next loop. In this example the termination condition is based on the
value of the counter variable, however that is not always the case. The termination condition may
be based on any of the variables in the main body of the loop and based on specific requirements
of the application. Do-Loops may be nested with each other and they may be nested within For-
Next loops and vice versa. All loops may be nested in conditional statements and vice versa.
In some cases it may be necessary to abruptly or prematurely exit a loop based on the progress of
the program. The syntax is
Exit Do
Or
Exit For
The program will exit the loop at the location the Exit code is written. The program will exit out
of the current (or most recent) loop. Typically the Exit command will be associated with some
conditional statement nested in the loop such that if that condition is met abort the loop and
move to some other area of the code or to some other relevant command. The Exit code can also
be called to exit out of a conditional statement (Exit If). The advantage of that being if for
example the conditional statement involves hundreds, if not thousands of conditions (including
composite conditions) and related code that need to be checked or evaluated, the program will
exit out once the first “True” condition is encountered, and not have to continue evaluating
through the other hundreds or thousands of other conditions and instructions.
Problem Statement:
A Florida bridge engineer maintains a large bridge inventory with the following attributes:
The inventory currently holds 15,332 records that are updated periodically by inspectors. The
engineer periodically performs spreadsheet calculations for update and reporting purposes. The
inspectors’ data entry requirements are different from what the engineer would prefer. For
example, the County Codes are given by the US Census Code number but the engineer would
prefer the name of the County. The engineer wants a button which when clicked on will run
through the entire data and for each record will conduct the following manipulations and
calculations:
At the beginning of the program the engineer wants pop up to appear stating the number of
records that are about to be manipulated and giving the engineer the options to continue or stop
the process. At the end of the process a pop up shall appear notifying the engineer that all
commands have been successfully executed.
As the program runs it will not be visually possible for the engineer to follow the calculations on
the screen. Set up a digital dashboard which displays the following information:
Solution:
Insert a command button onto the spreadsheet (alternatively, create a form and add a command
button onto the form)
Convert Census Code to Florida County name. The list of Florida counties by census code may
be downloaded from the internet. An abridged list is provided.
Consider the bridge data is stored on a spreadsheet named “bridges”. Also, the county code
number is in column “B” (column 2). So for the first record the reference to the county code
number will be
Sheets(“bridges”).cells(2, 2).value
Sheets(“bridges”).cells(3, 2).value
And so on.
Sheets(“bridges”).cells(i, 2).value
An If statement (or Select-Case statement) may be used to reference county code number to
county name as follows:
ElseIf ………………
:
End If
As there are 67 counties in Florida, the If statement will have 67 conditions to check. Note that in
this code, the name of the county will replace the county code number in column 2. If the intent
is to post the county name in a separate column, then the column number in the cells code must
be changed to that column number and the county name will now be posted in that column at
row i.
Next, assign the values of the input variables for the calculations. For example, age of bridge is
the current year (2014) minus the year built. The year built is in column “E” (column 5).
Note that a For statement must always have a corresponding Next statement at the bottom
otherwise the syntax is incomplete and a run-time error will occur
Now set up the digital dashboard. The purpose of the digital dashboard is to enable the user
“watch” the progress of the program as it moves down the table performing the calculations, as it
will be physically impossible to see the calculations in real-time as the computer monitor is not
large enough to display the entire spreadsheet of 15,332 records.
The progress of the program will therefore be monitored by viewing the dashboard information.
In the project, the client requested to be able to track the total number of records, the current
record being processed, and the number of records remaining to be processed, on the dashboard.
Dashboard
information
Next, add a message box at the end that alerts the user that the program has run to completion
It has been requested by the engineer that before the process runs a message box pops up giving
a caution that a large data set is about to be processed, and give the user the option to continue or
stop the process. Therefore before the For loop starts a message box with options must appear
Click on No.
Success.
Click Debug
The line where the error occurred is highlighted.
Study the code carefully.
The data from column 7 is actually the Average Daily Traffic, not Average Daily Truck Traffic.
Average Daily Truck Traffic will be calculated subsequently. Correct the variable name to
intAveDailyTraffic.
Click on Reset
The results so far are satisfactory. It can be concluded that the program is working as intended.
4. CONCLUSION
This course has presented a broad overview of fundamental concepts and principles of computer
programming, and presented them in situations encountered by practicing engineers and
scientists. All codes were developed using the Visual Basic for Applications (VBA)
programming language.
In this course the topics, conditional statements, message boxes and alerts, and looping structures
were covered in detail. Several examples from engineering were used to illustrate and
demonstrate the concepts and methods learned in this class. Two mini-projects were used to
demonstrate these programming concepts and methods in situations encountered by practicing
engineers.
This course has enabled participants to identify situations where programming is relevant and
will be of advantage to the professional. Practitioners are strongly encouraged to look out for
situations in their domains of expertise where programming solutions are applicable and will be
of benefit to their work and their organization.
Computer programming requires a careful and meticulous approach, and can only be mastered
and retained by practice and repetition.
REFERENCES
Bradley, J. C., & Millspaugh, A. C. (1999). Programming in Visual Basic 3.0. Irwin McGraw-
Hill.
FunctionX Inc. (2013). VBA for Microsoft Office Excel 2007. Retrieved December 21, 2013,
from FunctionX Tutorials: www.functionx.com/
Microsoft. (2013). Excel 2013 developer reference. Retrieved October 15, 2013, from Office
Dev Center: http://msdn.microsoft.com/en-us/library/office/ee861528.aspx