Você está na página 1de 51

Visual

Basic for Applications


Just Another
Programming Language


Author: Justin V. Conroy





Table of Contents
Document Scope ................................................................................................................................... 1
The Visual Basic for Applications Interface ............................................................................................. 2
Accessing the Developer Tab in Excel ................................................................................................ 3
Macro Security ................................................................................................................................... 5
Recording Macros .............................................................................................................................. 6
Data Types and Variables ...................................................................................................................... 7
Using Option Explicit Mode ............................................................................................................... 8
Declaring Variables ............................................................................................................................ 9
User Defined Functions ........................................................................................................................ 11
User-Defined Function - Example 1 Celsius to Fahrenheit Conversion Function ......................... 12
User-Defined Function - Example 2 Annual Compounding Function ........................................... 15
If Statements ....................................................................................................................................... 16
Basic If Statement ............................................................................................................................ 17
IfElse Statements ......................................................................................................................... 18
IfElseIfElse Statements .............................................................................................................. 19
Conditional and Logical Operators ................................................................................................... 20
If Statement Example 1 Letter Grade ...................................................................................... 21
If Statement Example 2 Leap Year .......................................................................................... 23
Select Structure ................................................................................................................................... 24
Select Structure Example 1 Radius Based Calculations ............................................................ 25
Select Structure Example 2 Rectangular Prism Equations ....................................................... 27
Defined Loops ..................................................................................................................................... 29
For Loops ......................................................................................................................................... 29
For Loop Example 1 Summation of Integers from 1 to N ......................................................... 30
For Loop Example 2 Compounding Interest with Monthly Deposits ......................................... 31
Conditional Loops ............................................................................................................................... 32
Do While Loops ............................................................................................................................... 32
Do Until Loops ................................................................................................................................. 32
Do Loop Example 1 Bessel Function ......................................................................................... 33
Do Loop Example 2 Taylor Series Expansion of ! ................................................................... 35
Objects, Properties, and Methods ........................................................................................................ 37

Accessing Excel Worksheets and Ranges ............................................................................................. 38


Range and Cells Objects .................................................................................................................. 38
Creating, Deleting, and Referencing Worksheets ............................................................................. 39
Subroutines ......................................................................................................................................... 41
Subroutines Example 1 Summation of Multiples ..................................................................... 41
Subroutines Example 2 Pulling It All Together ........................................................................ 42
Reference Libraries .............................................................................................................................. 44
Conclusion ........................................................................................................................................... 46

TABLE OF FIGURES
Figure 1: Windows Button ...................................................................................................................... 3
Figure 2: Excel Options Button .............................................................................................................. 3
Figure 3: Excel Options Popup Menu ...................................................................................................... 3
Figure 4: Developer Tab in Ribbon ......................................................................................................... 4
Figure 5: Options Menu ......................................................................................................................... 8
Figure 6: Require Variable Declaration Checkbox ................................................................................... 8
Figure 7: Insert Module ........................................................................................................................ 12
Figure 8: New Module - Option Explicit ................................................................................................ 12
Figure 9: Conversion Function Testing Spreadsheet Setup .................................................................. 14
Figure 10: Function Recognized by Excel ............................................................................................. 14
Figure 11: Full Usage of Function ......................................................................................................... 14
Figure 12: Annual Compound Interest Function in Use .......................................................................... 15
Figure 13: LetterGrade Test (Equations) ............................................................................................... 22
Figure 14: LetterGrade Test (Results) ................................................................................................... 22
Figure 15: Sphere Function Usage - Equation View .............................................................................. 26
Figure 16: Sphere Function Usage - Result View .................................................................................. 26
Figure 17: Sphere Function Usage - Input Comparison ......................................................................... 26
Figure 18: Rectangular Prism with Bisection Triangle ........................................................................... 27
Figure 19: Prism Function Testing - Equation View .............................................................................. 28
Figure 20: Prism Function Testing - Results View ................................................................................. 28
Figure 21: Solver Error ......................................................................................................................... 44

TABLE OF TABLES
Table 1: Data Types ............................................................................................................................. 10
Table 2: Conditional and Logical Operators ......................................................................................... 20
Table 3: Grade Assignments ................................................................................................................ 21
Table 4: Sphere Equations ................................................................................................................... 25
Table 5: Rectangular Prism Equations .................................................................................................. 27


DOCUMENT SCOPE
This document is intended for the use of learning a basic, introductory level knowledge of Visual Basic
for Applications and its applicability in engineering. It is the intent of this document to prepare the
reader with enough basic knowledge of Visual Basic for Applications so that further self study may
follow.
This document is not intended to cover all aspects of the Visual Basic for Applications programming
language but merely introduce the topic to the Computing for Engineers (CHEE 1331 / CIVE 1331 / IDNE
1331) Class at the University of Houston.
It is assumed that the student reading this document has already completed the majority of the course
listed above and that the student is proficient in solving engineering problems in Microsoft Excel and
Matlab 7. It is also assumed that the student has a firm grasp of the procedural programming aspect of
Matlab 7.
This document will make reference to the 2007 version of Microsoft Excel. All text in this document
formatted in the current font should be considered body text. Any text formatted in Courier New font
will be actual VBA Code.
This document is written in such a way that not all concepts can be obtained by reading the simple
explanations given. It is expected that the reader of this document will follow along and work each
example given as they read so that they can pick up on the smaller details that are built into the
examples.

THE VISUAL BASIC FOR APPLICATIONS INTERFACE


On all computers running the Windows operating system, there are a few different types of scripting
engines available for use; however this is not a well known fact. The scripting engine that will be used
when programming in Visual Basic for Applications (VBA) is known as the VBScipting Engine. This
engine can be accessed in a variety of different ways. For the focus of the class, the VBA Editor will be
used. This editor can be accessed through most of the Microsoft Office Applications and the user can
interface with them as he sees fit.
The VBA Editor can be accessed in almost the same manner, regardless of the Microsoft Office
Application being used. Although the student should have already been exposed to this editor in
Chapter 14 of the Excel textbook, Spreadsheet Tools for Engineers Using Excel by Byron Gottfried, this
document will cover some of the main points again.

Accessing the Developer Tab in Excel


The first step that should be taken when preparing to write VBA code for Excel should be to access the
Developer Tab. This tab opens up a variety of different options and functions which will be discussed
later in this document.
To access the Developer Tab, follow these steps:
1. Open Microsoft Excel 2007.
2. Click the Windows Button on the top left of the screen.


Figure 1: Windows Button

3. Click the Excel Options button near the bottom of the dropdown menu.

Figure 2: Excel Options Button

4. In the Excel Options popup menu, check the Show Developer Tab in Ribbon checkbox.


Figure 3: Excel Options Popup Menu

5. Click OK.


There should now be a Developer Tab for use in the Excel Ribbon.


Figure 4: Developer Tab in Ribbon

At this time, please take a moment to notice all of the different buttons and options available, even if
there is no understanding of them at the moment. It is important to have a feel of what options are
available to you before moving on to the next steps.

Macro Security
As you begin recording macros and writing VBA subroutines and functions, it is probable that the user
will encounter some Macro Security issues. It is important to understand why Microsoft places these
security measures into the software so that you can understand why your Macros may not be working.
Firstly, it is very possible for the writer of VBA script to have malicious intent. Along with that, it is
extremely easy for VBA to access the data layer of your computer, as well as the file system. Therefore,
it can be very easy for a person to write a malicious subroutine that will do a variety of different types of
harm to your computer. This is why Microsoft places security measures on Macros and Macro
containing workbooks. They simply want to be sure that any script that is executed was fully intended
to be executed by the user. Please keep this in mind when opening any files that other people send you.
With that being said, you may be prompted by Excel in a variety of ways that your Macros can not be
run for security reasons. If this occurs, it probably means that the Macro Security is set to disable the
Macro you are trying to run. It is not recommended, by Microsoft or the author of this document, but
the easy way around having Macro Security issues is to disable the security. Just be careful that you
dont open files that you dont trust if you choose to disable the security all together.

Recording Macros
Please refer to chapter 14 of Spreadsheet Tools for Engineers Using Excel by Byron Gottfried as it has an
excellent description of Macros, what they do, how they work, how to make them, and how to use
them.

DATA TYPES AND VARIABLES


In most programming languages, variables are not something to be taken lightly. In Matlab, when a
variable was needed, it was simply used without any worries or much more thought. In most
programming languages however, variable declaration is one of the most important aspects of a
program. Any variables used need to be declared first so that the compiler can know what data type it is
dealing with and how to treat it.
In VBA, there are two modes of operation that can be used. The default mode of operation allows
simple usage of variables without declaration. While this mode of operation can be easier, it is of poor
programming practice.
The other mode is called Option Explicit mode and this mode requires that all variables be declared
before use. While this option leads to more typing on the front end coding, it can make programs run
faster and it will also make them easier to debug. This option is also good in preparation for learning
other languages as most of the procedural programming languages used today require variable
declaration.
For the remainder of this document, Option Explicit will be used in all functions and subroutine
examples.

Using Option Explicit Mode


By default, this method is turned off. To turn it on, follow these steps:
1. Open the VBA Editor from Excel (Alt+F11)
2. Find the options button within the tool menu


Figure 5: Options Menu

3. Click the checkbox next to Require Variable Declaration


Figure 6: Require Variable Declaration Checkbox

4. Click OK
By activating this option, all variables will need to be declared before usage.

Declaring Variables
Declaring the proper variable types in VBA is a very important step. It lets the computer know how it
needs to handle your variables during calculations or procedural calls. The following table (obtained
from the Visual Basic Editor Help File) is a list of the data types that you may need to use in your
programs:


Data type
Byte
Boolean
Integer
Long
(long integer)
Single
(single-precision
floating-point)
Double

Storage size
1 byte
2 bytes
2 bytes
4 bytes

Range
0 to 255
True or False
-32,768 to 32,767
-2,147,483,648 to 2,147,483,647

4 bytes

-3.402823E38 to -1.401298E-45 for negative values;


1.401298E-45 to 3.402823E38 for positive values

8 bytes

-1.79769313486231E308 to

(doubleprecision
floating-point)

-4.94065645841247E-324 for negative values;


4.94065645841247E-324 to 1.79769313486232E308 for
positive values

Currency
(scaled integer)
Decimal

8 bytes

-922,337,203,685,477.5808 to 922,337,203,685,477.5807

14 bytes

Date
Object
String
(variablelength)
String
(fixed-length)
Variant
(with numbers)
Variant
(with
characters)
User-defined
(using Type)

8 bytes
4 bytes
10 bytes +
string length

+/-79,228,162,514,264,337,593,543,950,335 with no
decimal point;
+/-7.9228162514264337593543950335 with 28 places to
the right of the decimal; smallest non-zero number is
+/-0.0000000000000000000000000001
January 1, 100 to December 31, 9999
Any Object reference
0 to approximately 2 billion

Length of
string

1 to approximately 65,400

16 bytes

Any numeric value up to the range of a Double

22 bytes +
string length

Same range as for variable-length String

Number
required by
elements

The range of each element is the same as the range of its


data type.
Table 1: Data Types

10

USER DEFINED FUNCTIONS


As with most programming languages, being able to create user-defined functions can be one of the
most useful techniques in an engineers toolkit. When discussing Matlab, these user-defined functions
were mostly created as separate M-files which were called from other M-files. In VBA, it is not quite as
complicated once the general framework of a program has already been created.
At this time, enough general knowledge has been discussed to give a few examples of how to actually
implement some of these ideas. In the next two examples, a good understanding of user-defined
functions, variable types, and general VBA usage and execution should be realized.

11


User-Defined Function - Example 1 Celsius to Fahrenheit Conversion Function
Problem Statement: A common problem in Engineering is the multitude of units. Therefore, it can
sometimes beneficial to write a quick user-defined function to convert one unit to another. In this
example, create a simple user-defined function will be defined to convert temperature values from
degrees Celsius to degrees Fahrenheit.
Solution: The first step in writing this user-defined function is to open up the VBA Editor (Alt+F11). To
open up a new area to write code in (a Module), simply click the insert dropdown menu on the tool bar
and select Module.


Figure 7: Insert Module

After this step is completed, a new area will appear in the VBA Editor. If the Option Explicit mode has
been turned on, the words Option Explicit will appear in the topmost portion of the Module.


Figure 8: New Module - Option Explicit

12


This simply tells the compiler that you will need to declare all of your variables before anything can
execute. For the purposes of writing this function, the full code within the module will be given here and
it will be explained in detail thereafter.
Option Explicit
Function ConvertCtoF(degreesC as Double) As Double
Dim degreesF As Double
degreesF = degreesC * 1.8 + 32
ConvertCtoF = degreesF
End Function

The first line of this code, Function ConvertCtoF(degreesF as Double) As Double, tells the computer
many things. First of all, the word Function tells the VBA compiler that a function is being declared. It
knows that a function can either be called using other VBA code, or it can be called from within Excel!
This makes it very powerful.
The statement ConvertCtoF is an arbitrary name for the function being created. To make things easier
for the user, the purpose of the function was written into the name of the function itself.
The next part, (degreesF as Double), is where the input to the function is being declared. This
statement tells the compiler that it should expect something to be passed to it (either from other VBA
code or from Excel) and that it should store the value it is passed in the variable degreesF which is of
data type Double.
The final part of the first line, As Double, tells the compiler that the function itself should be considered
of type Double. This ensures that the output of the function has the correct data type for whatever is
going to use it.
The second line of code, Dim degreesC as Double, is the declaration of a variable that will be used in the
forthcoming code. The Dim Statement is short for Dimension. It simply tells the computer that a set
area of space is about to be reserved by a variable. In the same line, degreesC, is an arbitrary variable
name selected for use in the code. Finally, As Double, tells the compiler that the variable degreesC will
be of the Double data type.
The third line of code makes the necessary calculation of Celsius to Fahrenheit.
The fourth line of code assigns the output of the function. By typing ConvertCtoF = degreesC, the value
calculated and stored in the variable degreesC is passed to the function output, and therefore, passed
out of the function as the final answer.
The final line of code, End Function, simply tells the VBA compiler that the function declaration is over.

13


There are a variety of ways to test the function. For this example, it will be used in Excel to convert a
temperature. To test this particular function, go back to the Excel interface and create the following
spreadsheet:


Figure 9: Conversion Function Testing Spreadsheet Setup

Now, type =ConvertC into cell B2. It should be noticed that the user-defined function was recognized
by Excel and can be used like any other function:


Figure 10: Function Recognized by Excel

At this point, cell B1 should be referenced in the function.


Figure 11: Full Usage of Function

The final result of this example is a conversion of 100 degrees Celsius to 212 degrees Fahrenheit though
the use of the user-defined function .

14


User-Defined Function - Example 2 Annual Compounding Function
Problem Statement: Create a user-defined function that will calculate the amount of money
accumulated over a given period using a compound interest formula. It is important to note that this
examples purpose is to simply show another function definition. Microsoft Excel is already equipped
with many compound interest formulas.
In this example, it will be assumed that the user is only interested in annual compounding of his/her
money. The function will accept a principal amount, an interest rate, and a number of years to
compound. It will return the money accumulated at the end of the given period.
Solution: The full function will be shown here and explained thereafter.
Option Explicit
Function AnnualCompoundInterest(P As Double, I As Double, N As Integer) As Double
AnnualCompoundInterest = P * (1 + i) ^ N
End Function


The only real difference between this function, and the function in the first example, is that this
function has multiple input values. Instead of simply feeding the function one value, three separate
values are being passed to the function where the inputs are separated by commas.
This function is also written more simply than the last. Instead of creating a separate variable for the
calculation, the final value is simply passed directly to the output of the function. This saves on memory
and makes this function run faster.
To test the function, simply attempt usage using Excel:


Figure 12: Annual Compound Interest Function in Use

15

IF STATEMENTS
If Statements are one two types of decision making constructs that one can use when writing a
program. They allow the compiler to make decisions about what to do next in a program. This gives the
ability to have very robust programs that can handle anything a user may decide to try. In this section,
the basic syntax for the various types of If Statements will be given, as well as some of the conditional
operators. Finally, some examples will be shown that put If Statements to good use.

16

Basic If Statement
The following syntax shows how an If Statement should be declared. The text in bold is required while
the text in italics can vary depending on what you want to happen.

If condition Then
Code to Execute if condition was true
End If

17

IfElse Statements
The following syntax shows how an IfElse Statement should be declared. The text in bold is required
while the text in italics can vary depending on what you want to happen.

If condition Then
Code to execute if condition was true
Else
Code to execute if condition was false
End If

18

IfElseIfElse Statements
The following syntax shows how an If StatementElseIfElse should be declared. The text in bold is
required while the text in italics can vary depending on what you want to happen.

If conditionOne Then
[Code to execute if conditionOne was true]
ElseIf conditionTwo Then
[Code to execute if conditionTwo was true and conditionOne was
false]
...
ElseIf conditionN Then
[Code to execute if conditionN was true and condition(N-1) was
false.]
Else
[Code to execute if all conditions were false]
End If

19

Conditional and Logical Operators


In any of the previous If Statement declarations, the conditions used can be variable to what the user is
trying to achieve. Listed here are the conditional and logical operators used in VBA:
VBA Syntax

Purpose

<

Less Than

<=

Less Than or Equal To

>

Greater Than

>=

Greater Than or Equal


To

Equal To

<>

Not Equal To

And

And

Or

Or

Not

Not

Table 2: Conditional and Logical Operators

20


If Statement Example 1 Letter Grade
Problem Statement: Write a user-defined function that accepts a numerical value that represents a
students grade, and converts it into a letter grade based on the following table:

Numerical Grade

Letter Grade

90

80

75

70

<70

Table 3: Grade Assignments

Solution: This problem requires the use of an If Statement. The If Statement will determine where the
input grade falls and then return to the output the proper letter grade assignment. The full solution is
given here:
Function LetterGrade(numGrade As Double) As String
If numGrade >= 90 Then
LetterGrade = "A"
ElseIf numGrade >= 80 Then
LetterGrade = "B"
ElseIf numGrade >= 75 Then
LetterGrade = "C"
ElseIf numGrade >= 70 Then
LetterGrade = "D"
Else
LetterGrade = "F"
End If
End Function

There are a few things of note to discuss in this function. First of all, notice that in the function
declaration, the function itself is declared As String. This is important because the output of the
program is not a number. It is a string (in this case a single character) that the user is to understand.
Strings are an important concept to grasp because they show up everywhere in real world
programming.
Also, notice that because the output of the function is defined as a string, the assignment of the output
letter grades are executed using double quotation marks around the letters. This is how you tell VBA
that it is to understand the letters as a string of characters and not as code. Anything contained in
double quotation marks is considered a string.

21


As always, it is good to test user-defined functions to make sure they are working correctly. Like the
other user-defined functions created, this function can be tested in Excel. For that purpose, the
following simple spreadsheet was created:


Figure 13: LetterGrade Test (Equations)


Figure 14: LetterGrade Test (Results)

22


If Statement Example 2 Leap Year
Problem Statement: The leap year function is useful when data is taken over many years and the
engineer needs to correlate the data in terms of data per day. While assuming 365 days per year is okay
in some situations, it may not be for some particular problems.
The function to be written should accept a year and return to the user the Boolean response of TRUE if
the input year is a leap year and return a Boolean response of FALSE if it is not a leap year.
The rules for leap year determination are as follows:
1.
2.
3.
4.

All years evenly divisible by 400 are leap years.


Years not evenly divisible by 400 but evenly divisible by 100 are not leap years
Years not evenly divisible by 100 but evenly divisible by 4 are leap years
All other years are not leap years

Solution: The solution to this problem requires the use of an If Statement, as well as the modulus
function. In VBA, the modulus function syntax is as follows:
X Mod Y
The function will return the remainder of X divided by Y.
With this information, the solution to the problem statement above can be obtained with the following
code:
Option Explicit
Function LeapYear(year As Long) As Boolean
If year Mod 400 = True Then
LeapYear = True
ElseIf year Mod 100 = True Then
LeapYear = False
ElseIf year Mod 4 = True Then
LeapYear = True
Else
LeapYear = False
End If
End Function

Two items of interest should be explained in this solution. Firstly, the variable year is dimensioned as a
Long number. Refer back to the table of variable types to see that a long number is simply an integer
that can be of large value. This is done so that if the user chooses to test a year that is greater than the
year 32757, the function will still work properly.
Secondly, notice that the function output is dimensioned as Boolean. This allows the function to pass
values of TRUE and FALSE as output.

23

SELECT STRUCTURE
A Select Statement works in much the same way that an If Statement works. It has some condition
that must be met and it executes different bits of code accordingly. The general syntax of the Select
Statement is as follows:
Select Case variable
Case condition1
[Code to execute if variable = condition1]
Case condition2
[Code to execute if variable = condition2]
Case condition3
[Code to execute if variable = condition3]
...
Case conditionN
[Code to execute if variable = conditionN]
Case Else
[Code to execute if variable did not equal any conditions]
End Select
While the general syntax will most probably be applied to most situations, it is important to note that
like the If Statement, the number of Cases and the necessity of the Case Else statement is completely
up to the users discretion. These ideas and some slight modifications to the general syntax will be
illustrated in the following examples.

24


Select Structure Example 1 Radius Based Calculations
Problem Statement: Write a user-defined function that accepts two inputs. One input should be a
radius and the other input should be a letter (V,SA,D,AP) that represents the calculation desired by the
user. If the user chooses V, the function should calculate and output the volume of a sphere with the
specified radius. If the user chooses SA, the function should calculate and output the surface area of a
sphere with the specified radius. If the user chooses D, the function should calculate the diameter of a
sphere with the specified radius. If the user chooses AP, the function should calculate and output the
area of the plane square/plane that would fit inside of the center of the sphere. And finally, if the user
does not enter a valid selection, the function should output zero.
Solution: The first step in this solution is to determine the various equations that will be required for this
function to operate. The following equations are required for the function to operate:

Volume

4 !

3

Surface Area

= 4 !

Diameter

= 2

Area of Plane

= 2 !

Table 4: Sphere Equations

Now that the equations are defined, the user-defined function is as follows:
Option Explicit
Function Sphere(R As
Select Case opt
Case "V"
Sphere =
Case "SA"
Sphere =
Case "D"
Sphere =
Case "AP"
Sphere =
Case Else
Sphere =
End Select
End Function

Double, opt As String) As Double


(4 / 3) * WorksheetFunction.Pi() * R ^ 3
2 * WorksheetFunction.Pi() * R ^ 2
2 * R
2 * R ^ 2
0

There are two important things to note about this function. Firstly, notice that the opt variable is
defined as a string. This means that the user will need to call the function using letters between double
quotes. This can be seen below in the test of the function.

25


Secondly, notice the call of the number Pi. Excel stores the number in its own functions and in this
example, it is shown that all of the normal Excel functions can be called by using the
WorksheetFunction object. More will be discussed about objects in later sections of this
document. The import thing to realize for now is that the number Pi is not something that the VBA
compiler stores in its memory, therefore, the user must find the number from within Excels own
memory. For now, take a moment to see all the different methods that the WorksheetFunction has
to offer by typing WorksheetFunction. in the VBA editor.
As an example of the use of this function, the following screenshots were taken:


Figure 15: Sphere Function Usage - Equation View


Figure 16: Sphere Function Usage - Result View

Take a few minutes to notice that if the user does not feed the function a cell, the user can feed the
function the inputs directly. However, if the user does not place the opt variable inside double
quotation marks, the VBA compiler will not understand that the input is a string and return an error:


Figure 17: Sphere Function Usage - Input Comparison

26


Select Structure Example 2 Rectangular Prism Equations
Problem Statement: Write a user-defined function that will accept the input of Length, Width, Height,
and a calculation choice of either SA, V, or LBH. When the user enters a choice of SA, the
function should output the surface area of the rectangular prism. When the user enters a choice of V,
the function should output the volume of the rectangular prism. When the user enters a choice of LH,
the function should output the length of the hypotenuse of the triangle that fits inside of the prism and
bisects it diagonally (See Figure Below). Finally, if the user does not enter a recognized choice, return a
zero.


Figure 18: Rectangular Prism with Bisection Triangle

Solution: Much like the last example, the first step in solving this problem is to gather the equations
needed to make the necessary calculations. After some simple geometric analysis, the following
equations can be derived:

Surface Area

= 2( + + )

Volume

Length of Hypotenuse

! + ! + !

Table 5: Rectangular Prism Equations

Now that the equations are defined, the user-defined function is as follows:
Option Explicit
Function Prism(L As
Select Case opt
Case "SA"
Prism =
Case "V"
Prism =
Case "LH"
Prism =
Case Else
Prism =
End Select
End Function

Double, W As Double, H As Double, opt As String) As Double


2 * (H * W + L * H + L * W)
L * W * H
Math.Sqr(L ^ 2 + W ^ 2 + H ^ 2)
0

27


The only noteworthy item in this solution is the use of the Math object. Like the
WorksheetFunction object used in the previous example, more will be discussed on objects later.
For now, take a moment to look at all of the different methods the Math object has to offer by typing
Math. in the VBA editor.
As always, test the function in Excel to ensure proper functionality.


Figure 19: Prism Function Testing - Equation View


Figure 20: Prism Function Testing - Results View

28

DEFINED LOOPS
Like other programming languages, VBA has the power to execute a massive amount of calculations in
a very short amount of time through the use of an iterative tool called a loop. There are two different
general types of loops that the user can implement: a defined loop and a conditional loop. In this
section, the defined loop will be discussed.

For Loops
In VBA, defined loops are called For Loops. These loops are the tool that should be used when it is
desired to run a defined number of iterations. The general syntax of a For Loop is given here:

For variable = intialValue To finalValue Step incrementValue


[Code to execute during the iterative loop]
Next variable
In the following examples, the For Loop will be put to use and discussed in detail.

29


For Loop Example 1 Summation of Integers from 1 to N
Problem Statement: Write a user-defined function that will accept an input of an integer N. The output
should be the summation of all positive integers from 1 to N (i.e. 1 + 2 + 3 + + N).
Solution: This problem is a simple For Loop example. The solution is as follows:
Option Explicit
Function SummationN(N As Long) As Long
Dim i As Long
SummationN = 0
For i = 1 To N Step 1
SummationN = SummationN + i
Next i
End Function

A few things are of note in this function. Firstly, both N and the function output itself are defined as
Long. This ensures that the function will be able to handle large integers if necessary. Secondly, the
iteration variable i must be defined before use as the Option Explicit method has been
activated. Lastly, unlike most of the other examples in this document, the function output
variable/name, SummationN, changes many times throughout the function execution. However, only
the final value stored in the SummationN variable is passed as the output when the function
terminates.
Many examples of how to test functions have been shown in this document. For the purpose of
conciseness, the testing of this function will not be shown.

30


For Loop Example 2 Compounding Interest with Monthly Deposits
Problem Statement: Write a user-defined function that will accept four inputs: Principal deposit
amount, monthly deposit amount, annual percentage interest rate (as a fraction), and savings period
(time in years).
The function should simulate the scenario where a person opens a savings account at a given interest
rate with a principal deposit and where the person will make monthly deposits into the savings account.
It should be assumed that the interest compounds at the end of each month. It should also be assumed
that the person makes their monthly deposit at the end of each month as well.
The function should output the total money accumulated at the end of the savings period.
Solution: The function solution is as follows:
Option Explicit
Function SavingsAccount(P As Double, D As Double, r As Double, t As Long) As Double
Dim year As Long
Dim month As Integer
SavingsAccount = P
For year = 1 To t
For month = 1 To 12
SavingsAccount = SavingsAccount * (1 + r / 12) + D
Next month
Next year
End Function


It is important to note that this problem could have been solved in various ways. However, in this
solution, two For Loops were used to simulate the total years and the monthly contributions from
interest and deposits. So, for each year that the savings account is active, each month is simulated
individually where the interest gets compounded and the monthly deposit is made.
Many examples of how to test functions have been shown in this document. For the purpose of
conciseness, the testing of this function will not be shown.

31

CONDITIONAL LOOPS
Conditional Loops can be of major value in programming. In VBA, there are two different types of
conditional loops, however they work in the same ways. Both types of conditional loops will iterate
during the period in which some condition is true/false (depending on the loop type) and they will cease
when the condition is true/false (depending on the loop type). Having this flexibility is convenient
because not all people think in the same ways and both of these loops can perform the same exact task.
Most people will ultimately choose to use only one of these loops, but either loop can be written to
perform the task of the other. This concept will be demonstrated with examples later.

Do While Loops
A Do While Loop is a conditional loop that executes code while some condition is true. Therefore,
code execution will continue until the condition becomes false. The general syntax is as follows:
Do While condition
[Code to execute while the condition is true
Or
Code to execute until the condition becomes false]
Loop

Do Until Loops
A Do Until Loop is a conditional loop that executes code until some condition is true. Therefore, code
execution will continue so long as the condition is false. The general syntax is as follows:
Do Until condition
[Code to execute while the condition is false
Or
Code to execute until the condition becomes true]
Loop

32


Do Loop Example 1 Bessel Function
Problem Statement: One of the most important differential equations in applied mathematics is
Bessels differential equation. The solution is known as the Bessel function of the first kind (n=1):
!

! =

!
!!!

1 ! !!

2!!!! ! + !

Write a user-defined function that will accept a value, X, as the input and return the value of the Bessel
function at the given X value.
Solution: It is important to note that Excel already holds the capability of making this calculation using
the BESSELJ function. However, for purposes of the example, the user will create their own custom
function to perform the same task. Also, for this problem, two solutions will be given, one using a Do
While loop and one using a Do Until loop.
The Do While loop solution is as follows:
Option Explicit
Function Bessel(x As Double) As Double
Dim n As Integer, m As Long
Dim sumTerm As Double, converganceCheck As Double, _
oldTerm As Double, newTerm As Double
Dim tolerance As Double
sumTerm = 0
m = 0
n = 1
converganceCheck = 100
tolerance = 0.000001
Do While converganceCheck > tolerance
oldTerm = sumTerm
sumTerm = sumTerm + ((-1) ^ m * x ^ (2 * m)) / (2 ^ (2 * m + n) * _
WorksheetFunction.Fact(m) * WorksheetFunction.Fact(n + m))
newTerm = sumTerm
converganceCheck = Abs(oldTerm - newTerm)
m = m + 1
Loop
Bessel = x ^ n * sumTerm
End Function


The programming scheme for solving this problem has been explained many times throughout the
course, so for purposes of conciseness, the explanation will not be given.
In terms of the actual VBA coding though, there are a few things to note about this function. Firstly, in
the variable declaration list near the top of the function, it can be seen that there are two different ways
to declare variables. In previous functions, each variable was declared on a separate line, however it can

33


be seen in this function that variables can be declared on the same line by use of a comma separator. It
is important that the variable type still be declared after the variable.
Secondly, a continuation marker was used in two places in this function. Just as in Matlab coding, it can
sometimes be useful to continue the code of one line in a second line of code. In Matlab, this was done
with an ellipsis (). In VBA, a line continuation is denoted by an underscore (_). This can be seen in
the variable declaration list, as well as the summation term in the Do Loop. It simply tells the compiler
that the code on the second line is to be considered as part of the first line.
The Do Until Loop solution will be given here, however no explanation will be given as most of the
coding is the same as the solution above. The only changes are in the Do Loop declaration line.
Option Explicit
Function Bessel(x As Double) As Double
Dim n As Integer, m As Long
Dim sumTerm As Double, converganceCheck As Double, _
oldTerm As Double, newTerm As Double
Dim tolerance As Double
sumTerm = 0
m = 0
n = 1
converganceCheck = 100
tolerance = 0.000001
Do Until converganceCheck < tolerance
oldTerm = sumTerm
sumTerm = sumTerm + ((-1) ^ m * x ^ (2 * m)) / (2 ^ (2 * m + n) * _
WorksheetFunction.Fact(m) * WorksheetFunction.Fact(n + m))
newTerm = sumTerm
converganceCheck = Abs(oldTerm - newTerm)
m = m + 1
Loop
Bessel = x ^ n * sumTerm
End Function

34


Do Loop Example 2 Taylor Series Expansion of
Problem Statement: A common converging series used in engineering is the Taylor Series. One use of
this series is to approximate values for ! . So, for the complete Taylor Series expansion, ! can be
approximated to:
! ! !
!
1+
+
+
++
=
1! 2! 3!
!

!!!

!

!

Write a function that will accept an input of and calculate the approximation of ! using the Taylor
Series Expansion.
Solution: As there is not much difference in this solution as compared to the last example, the solution
to the problem using a Do While Loop and a Do Until Loop will simply be shown with no explanation.
Using a Do While Loop:
Option Explicit
Function TaylorSeries(x As Double) As Double
Dim n As Long
Dim converganceCheck As Double, tolerance As Double
Dim sumTerm As Double, oldTerm As Double, newTerm As Double
n = 0
converganceCheck = 100
sumTerm = 0
tolerance = 0.000001
Do While converganceCheck > tolerance
oldTerm = sumTerm
sumTerm = sumTerm + (x ^ n) / WorksheetFunction.Fact(n)
newTerm = sumTerm
converganceCheck = Abs(oldTerm - newTerm)
n = n + 1
Loop
TaylorSeries = sumTerm
End Function

35


Using a Do Until Loop:
Option Explicit
Function TaylorSeries(x As Double) As Double
Dim n As Long
Dim converganceCheck As Double, tolerance As Double
Dim sumTerm As Double, oldTerm As Double, newTerm As Double
n = 0
converganceCheck = 100
sumTerm = 0
tolerance = 0.000001
Do Until converganceCheck < tolerance
oldTerm = sumTerm
sumTerm = sumTerm + (x ^ n) / WorksheetFunction.Fact(n)
newTerm = sumTerm
converganceCheck = Abs(oldTerm - newTerm)
n = n + 1
Loop
TaylorSeries = sumTerm
End Function

36

OBJECTS, PROPERTIES, AND METHODS


VBA has the capability of delving into an entirely different form of programming, known as Object
Oriented Programming. It is well beyond the scope of this document and the CHEE/CIVE/IDNE 1331
course to learn how to program in this way. However, it is important to understand some of the basic
terminology of object oriented programming so that better understanding of the VBA interface can be
realized.
By now, the reader of this document should have noticed that when certain words are typed into the
VBA editor, with the addition of a period, a list of items will automatically pop up. For example, when
the user types WorksheetFunction. into the VBA editor, a list appears with all of the functions
available for use in Excel.
What is happening in these situations is that Objects are being accessed. So in the example above, a
WorksheetFunction is actually an Object and the list of functions being accessed is known as a list
of Methods.
An Object can be defined as anything that can have a Property or a Method. Most literature written on
object oriented programming will make an analogy to the fact that an object can be any every-day item
and that most every-day items can have attributes like color, weight, dimensions, etc. (properties), and
some object can even do things like sit, stand, run, jump, etc. (methods).
With this in mind, go back to the second example using the Select Structure. It was necessary to take
the square root of a number so the solution shows usage of the Math.Sqr method. In this case, Math
is the object in question that contains a list of mathematical methods and Sqr is the method chosen
to use in the example, which takes the square root of a number.
The same can be seen for the WorksheetFunction.Fact in the Do Loop examples. In these cases,
WorksheetFunction is the object that contains many methods for use by the user, and the Fact
method used takes the factorial of a number.
These two objects are good examples of objects that only contain methods. However, many objects
can contain method, properties, or even sub objects. More on this will be described in the next section.

37

ACCESSING EXCEL WORKSHEETS AND RANGES


Sometimes it is necessary for VBA code to access aspects of an Excel document. Some examples of
these types of programs will be given in the next section. In this section, a general sense of how to
interface with Excel through VBA will be discussed.

Range and Cells Objects


There are several ways to pull information from an Excel document into VBA for any use that the user
sees necessary. The two ways of obtaining information from cells in Excel that will be discussed here
will be through the use of the Range and Cells Objects. While both of these objects offer many of
the same methods and properties, the use of one may sometimes be preferred over the other.
The Range object can be used when it is desired to reference cells using the normal Excel syntax. For
example, if the user wanted to pull information out of cell A5 in an Excel worksheet and put it in a
variable (K for example), then the code is simply K = Range(A5).
Contrarily, if the user did not want to use the normal Excel referencing syntax, and preferred rather to
choose a cell based on its row/column position in a worksheet, then the user could choose to use the
Cells object. For example, if again the user wanted to pull information out of cell A5 and put it in the
variable K, then the code would be K = Cells(5,1). In this case, the 5 represents the 5th row in the
worksheet and the 1 represents the 1st column in the worksheet.
Both methods of pulling information from Excel can be of benefit in different situations, therefore both
of them should always be considered as one choice may be better than the other depending on what
the user is trying to accomplish.
Both the Range and the Cells object have useful properties and methods that can be used to
accomplish many tasks in VBA coding. For example, if it is necessary to select a certain cell so that
some code may be applied to the currently selected cell, both objects offer the Select method. Using
the Range(F6).Select or Cells(6,6).Select methods are the equivalent of clicking the
given cell with a mouse.
Other important properties of the Range and Cells objects are the Row, Column, and Address.
These properties all allow the user to obtain information about the location of a given cell within a
worksheet as sometimes, the location is not defined by the user, but it needs to be known. So, using the
Row property will return the row number where the cell is located, the Column property will return the
column number where the cell is located, and the Address property will return the absolute address of
the cell being referenced. It is best to try these properties out and discover how to put them to use with
some self study.
One more important property of the Range and Cells objects worth mentioning is the Offset
property. Offset allows the user to write code based on some current cell, and allows for referencing
of cells around the current cell. For example, Range(A1).Offset(4,5) will reference cell F5,
rather than A1 because F5 is 4 rows offset from A1 and 5 columns offset from A1.

38


Along with pulling information from an Excel worksheet into the VBA coding, it is also possible to send
information from VBA into an Excel document by using the Range and Cells objects.
For example, if the user desired the number 5 to be placed in Cell C6, then the user would simply use
Range(C6) = 5. Or, Cells(6,3) = 5 could also be used.

Creating, Deleting, and Referencing Worksheets


Another important object that maybe be frequently used is the Sheets Object. This object can be
used in conjunction with the Range and Cell objects to define what sheet should be used when grabbing
or populating data. For example, if the user wanted cell B8 on Sheet3 to be populated with the letter
G, then the Sheets(Sheet3).Range(B8) = G can be used.
Keep in mind that if the user does not specify the sheet, the compiler will assume that the Range or
Cells being referenced are on the current ActiveSheet. If it is more convenient to declare an
active sheet, and then grab or populate data, sheets can be activated using the Activate method.
Simply use Sheets(SheetNameHere).Activate to activate any desired sheet.
It can sometimes be convenient to have the VBA compiler create or delete sheets in a workbook. This
can be useful when creating more complex subroutines as it will allow the population of a clean sheet
for each run of the code. This way, there would be no confusion about what is currently on a worksheet
or what is not on a worksheet.
In the authors experience, in these situations it is usually best to tack on a bit of code at the beginning
of a subroutine to make sure that there is always a clean slate. At this time, the code will be given and
discussed thereafter. Note that there are some new concepts being shown in this example
Option Explicit
Sub DeleteSheetsExample()
Dim currentSheet As Worksheet
Application.DisplayAlerts = False
For Each currentSheet In ActiveWorkbook.Sheets
If currentSheet.Name = "MySheet" Then
currentSheet.Delete
End If
Next currentSheet
Sheets.Add.Name = "MySheet"
Application.DisplayAlerts = True
End Sub

As this program has a few new items a detailed discussion of this program will be given:

39


The first line, Option Explicit is nothing new. Again, this simply tells the compiler that variables
need to be declared.
The next line, Sub DeleteSheetsExample(), is the declaration of the subroutine. A subroutine is
just a program that does something, but doesnt necessarily have any outputs. More will be discussed
on subroutines in the next section.

The next line, Dim currentSheet As Worksheet, is a different twist on normal variable
declaration. Rather than declaring a variable as a data type, which was done in all the other examples in
this document, the variable here is being declared as an object. This allows the variable to have all the
same properties and methods associated with the Worksheet object.

The next line, For Each currentSheet In ActiveWorkbook.Sheets, is the declaration of
a different type of For Loop. While it works the same as any other For Loop, instead of iterating a
specific number of times, it simply iterates through a defined set of objects. In this case, the compiler
will loop through each sheet in the active workbook, temporarily assigning each sheet to the variable
currentSheet. This allows the user to do things with each sheet individually. Note that For Each
can be used on a variety of objects like sheets in workbooks (seen here), cells in ranges, files in folders,
etc.

The next line, If currentSheet.Name = "MySheet" Then, checks to see if the name of the
currentSheet (the sheet being iterated through at the time) is equal to MySheet, an arbitrary
sheet name. If the name of the focus sheet happens to be MySheet then the compiler will execute the
next line, currentSheet.Delete, which will delete the sheet. After this, the If statement and the
For Loop are both terminated using their specific termination statements.

Finally, after the loop has been executed, it is assumed that at this point, there exists no sheet called
MySheet. So now, it can be recreated using the line Sheets.Add.Name = "MySheet".

There are two more statements that were not discussed yet. The two lines
Application.DisplayAlerts = False and Application.DisplayAlerts = True
serve an important purpose. If these two lines were not written into the code, Excel would throw a
warning message each time a sheet deletion is attempted. The first line,
Application.DisplayAlerts = False, turns off the warning message so that it doesnt pop
up during code execution. The second line, Application.DisplayAlerts = True, turns the
messages back on so that the user isnt surprised by anything that they may be trying to do later. Try
the code without these two lines to see what happens.

40

SUBROUTINES
Subroutines are something that should not be new. In Matlab, any script file that was not a function
could have been called a subroutine; however this word was not used in the course until this time.
These types of programs were also seen when Macros were recorded previously in the course.
Subroutines can be an excellent tool at the disposal of a programmer because they do not require any
input variables (however it can if needed). This allows for clean, concise code that is easier to debug. It
should be noted that most programmers will make separate subroutines for separate tasks.
As usual, it is best to see this in action.
Subroutines Example 1 Summation of Multiples

Problem Statement: Write a VBA subroutine that will sum up all the multiples of 3 and 5 that are
between zero and 1,000,000 and display the result in a message box.
Solution: As there are a few new things being introduced in this problem, the solution will be given here
with a brief explanation of the new material afterwards.
Option Explicit
Sub SumMultiples()
Dim i As Long, sumTerm As Long
sumTerm = 0
For i = 1 To 10000
If i Mod 3 = 0 Or i Mod 5 = 0 Then
sumTerm = sumTerm + i
End If
Next i
MsgBox "The result is: " & sumTerm
End Sub

The two main differences in this program versus most of the functions in this document start with the
second line of code. Instead of declaring Function, the word Sub is declared. Sub is short for
Subroutine and as started above, subroutines do not require that there be any input or output. They
simply exist to perform tasks. This subroutine is an example of such a task. Code is executed inside the
subroutine but it does not require any input from an outside source, nor does it need to communicate
with an outside source (Excel/Functions/Other subroutines). The only indication that the user gets from
this subroutine that it actually ran is the message box that is displayed at the end. Without it, the user
would never even know that the subroutine was actually run.

41


The second new item is the message box itself, called by using the MsgBox command. In this line of
code, it can be seen that the message box can contain complex strings of information to be displayed.
In this example, the The result is: is actually a string of characters. The compiler knows this
because all of the characters are contained between double quotation marks. The ampersand (&) sign
is a concatenation character which puts multiple strings or objects together. In this example, the
message box displays the first string of characters and then connects the variable sumTerm to the end
of the string. This way, the user of the program sees a clean, easy to understand message box.
Subroutines Example 2 Pulling It All Together
Rather than giving a problem statement, this example is simply here to show how subroutines and
functions can be used together to create powerful programs in VBA. While this program is not going to
actually accomplish anything worthwhile, it is here simply to show how some of the functions and
subroutines in this document can be intertwined to create something larger.
Option Explicit
Sub BringItAllTogether()
Dim e As Double
Dim money As Double
DeleteSheetsExampleModified ("SomeNewSheet")
e = TaylorSeries(1)
money = SavingsAccount(10000, 500, Bessel(0.5), 20)
Sheets("SomeNewSheet").Range("A1") = e
MsgBox "Money = " & money & vbNewLine & "e ~ " & e
End Sub

In this example, the first task is to define the variables e and money. These will be used later in the
program.
The second major task is to use a modified version of the DeleteSheetsExample subroutine created in
the previous section of this document. It was modified to accept a sheet name as a string input and
then create a sheet with the given name after deleting any sheets with the same name. Try this one out
on your own.
Once that is done, the subroutine assigns a value of the result of the TaylorSeries function to the
variable e. Then, the variable money gets assigned a value which is the result of the SavingsAccount
function. Notice that the interest rate assigned to the SavingsAccount function is the result of the
Bessel function where x is equal to 0.5. This is an example of a function with another function
embedded inside.

42


Finally, Range A1 is assigned the value of e and a message box is populated with the values of
money and e for the user to see. Notice that in this message box, numerous strings and values were
concatenated together with the use of the ampersand. Also, there is a keyword, vbNewLine, which
tells the compiler to move to the next line before writing the next information into the message box.
This is equivalent to a return carriage (pushing enter on your keyboard).

43

REFERENCE LIBRARIES
There is one final item that needs to be discussed in this document. Before it is introduced, the reader
of this document should now be well versed in writing functions, subroutines, and recording macros. So
for this example, take a moment to try to accomplish something. Go ahead and take a moment to
record a macro that uses Excels Solver feature. It doesnt have to do anything special, just make sure
the macro recorder is turned on, solve something with solver, and then stop the recorder. What
happens when you try to execute the macro? Unless you have read ahead and fixed the problem in
advance, you should be seeing an error like this:


Figure 21: Solver Error

So what is wrong? This error plagues many engineers who are well versed in recording macros, but not
in writing VBA code. In fact, finding help on this particular issue is not always easy.
Firstly, let it be known that there is nothing wrong with the code, or the compiler. Everything is exactly
as it should be. The problem lies in what are known as references.
There is an entire library of coding objects that can be accessed through VBA. These libraries allow VBA
to interface with everything from Adobe, the computers file system, complex SQL databases, etc. So
the problem here is that Solver Code is stored in a separate library that is not built into the VBA
compiler. For this reason, it must be activated before any Solver code can be executed.
To fix this problem, follow these steps:
1) Push the Stop button to reset the VBA compiler
2) Click on Tools References

44


3) Make sure the checkbox next to SOLVER is checked, then push OK.
At this point, the compiler now knows where to look for Solver code, so it now knows how to execute it.
Now, when the Solver macro is executed, everything will work as it should.
Take a look at the list of references again. Notice that there are hundreds of reference libraries that can
be accessed. It is not in the scope of this document to cover any more of them; however, it is good to
know that they exist.

45

CONCLUSION
It is important to understand that this document does not cover everything. This is only the tip of the
iceberg when it comes to the possibilities at hand with VBA coding. Dont forget that there are many
references online that are available to the reader. Simply typing the words How To VBA
insertTopicHere into a Google search will most likely answer any questions that may arise with
regards to topics not covered by this document. In this authors experience, 99.99% of the problems
that may arise have arisen to someone else in the past, and they have probably written about it online.

46

Você também pode gostar