VBA Programming in Excel For Decision Support Systems

You are on page 1of 22
At a glance
Powered by AI
The key takeaways are that VBA can be used to create user-friendly applications in Excel for modeling and decision support, VBA code is stored and run from modules and macros, and variables, constants, and functions are important elements of VBA programming.

A Decision Support System has three main components - the front end for user input, the model which can be hidden, and the back end for presenting results in a nontechnical format.

Visual Basic for Applications (VBA) is a programming language that can be used to automate tasks and add functionality to Microsoft Excel. VBA code is stored in modules and macros and allows for things like loops and user interaction that simple recorded macros cannot perform.

MgtOp 556—Advanced Business

Modeling

Professor Munson

Topic 1
VBA Programming in Excel for
Decision Support Systems

(Set 1—VBA Basics, Input/Message Boxes,


Interacting with the Spreadsheet, VBA
Constants, Using Excel Functions in VBA,
String Functions and User-Defined
Functions)

“VBA is a relatively easy programming language to master. This makes


it accessible to a large number of nonprofessional programmers in the
business world—including you.”
Albright, S. Christian, VBA for Modelers, 5th Ed., Cengage Learning, 2016, p. 9
Decision Support System (DSS)
For modeling, a DSS represents a user-friendly
application.

Front end—dialog boxes for users to insert data

Model—may be hidden to the user

Back end—nontechnical report of results

Visual Basic for Applications


Recorded macros work well for certain tasks,
but cannot perform others (such as loops). In
general, the more user interaction there is, the
more likely VBA code might be worthwhile.

Note that VBA is similar, but not equivalent to,


Visual Basic. VBA applies directly to features
of an application such as Excel. VBA code can
be written for Microsoft Word as well.

VBA applies logic behind the scenes.


Files
Must be saved as macro-enabled workbooks
(.xlsm as opposed to .xlsx)

Enable macros by selecting


→File→Options→Trust Center→Trust Center Settings→
Macro Settings

Definitions
Objects correspond to nouns, properties
correspond to adjectives, methods correspond to
verbs, and arguments correspond to adverbs.

Collection objects (these are plural) contain all


individual objects of a certain type

The Visual Basic Editor (VBE)


The VBE is the programming workspace. It’s
easy to toggle back and forth (<ALT>< F11>)
between the Excel worksheets and the VBE.

Help
Object Browser (<F2>)
Lists all objects, properties, and methods
Locals Window Quick Watch
Displays values Selects a variable to
of all variables display value in the
Watch Window

Immediate Window
Lets you enter and test a
single line of code
outside of the SUB

Code is stored in a module. →Insert→Module


Start a SUB (subroutine)
→Insert→Procedure [type in a name] →OK
(the name must be a single word)
Put all commands between:
“Public Sub name()” and
“End Sub”
In general, have separate SUBS for separate
tasks (a macro is a SUB).
To run a SUB, press <F5>.
To step through 1 line at a time, press <F8>
Setup
Check:
→Tools→Options→Editor→Require Variable Declaration

Uncheck:
→Tools→Options→Editor→Auto Syntax Check

Typing
Indent for readability (use the <Tab> key or
→Edit→Indent). To remove an indentation, use
<Shift><Tab> or →Edit→Outdent)
Add blank spaces for readability
To wrap a line, insert a blank then _ then a blank;
otherwise, each new line is considered to be a
separate command
Insert comments with a single quotation mark
Red color: you typed something wrong
Blue color: for all keywords (Sub, End, For)
Green color: for all comments

SAVE OFTEN!
Variables
Variables contain values or strings of text and
can be modified during the course of a program.

They must be declared with a Dim statement:


Dim [variable name] As [type of variable]

Rules for Variable Names


1. Begin the name with letter
2. The name cannot contain spaces
3. Needs to be different than the name of the SUB

Most Common Variable Types


o String (for text such as “Bob”)
o Long (for integers) [Use Variant if < 2.1 billion]
o Double (for decimal numbers)
o Boolean (for variables that can be True or False)

If a variable appears to the left of an equals sign,


then its new value in memory becomes
whatever is on the right of the equals sign.
To assign a value to a variable:
unitCost = 1.20
unitsSold = 20
totalCost = unitCost * unitsSold
totalCost = totalCost + 20
TeamName = “Tigers”
Input Boxes and Message Boxes
Two VBA built-in functions:
InputBox(prompt to user in quotes, title in quotes)
(the title is optional)

The following creates an input box called “Selling price”


that asks the user to “Enter the product’s unit price.” The
value is stored in the variable called “price”.
price = InputBox(“Enter the product’s unit price.”, “Selling price”)

MsgBox(statement in quotes, button, title in quotes)


(the button indicator and title are optional)

The following creates a message box called “Selling price”


that states the price and includes an “information” button.
MsgBox “The product’s unit price is $2.40.”, vbInformation, “Selling price”

Note: No parenthesis around the message box command


that simply displays the box.
Yes-No Input
To create a Yes-No box for user input into a box labeled
“Chance to quit” that would store either vbYes (6) or vbNo
(7) in the Long (not Boolean) variable “result”, use the
following message box (not input box) command:
result = MsgBox(“Do you want to continue?”, vbYesNo, “Chance to quit”)

Other options:
vbOKCancel, vbAbortRetryIgnore, vbRetryCancel,
vbYesNoCancel, vbOKOnly

You can use the InputBox and MsgBox functions in the


same line, as in:
MsgBox InputBox(“Type your name”, “User’s name”), vbExclamation, “User’s Name”
Strings
A string is simply text, surrounded by double
quotes.

To concatenate two strings together, use the


ampersand (&).

The following SUB gets a product’s name and


then displays it in a message box:
Sub GetProductName()
Dim product As String
product = InputBox("Enter the product's name.")
MsgBox "The product's name is " & product & ".", vbInformation
End Sub

To insert a carriage return (start on a new line)


in a message box, put the following between the
first line and the second line: & vbNewLine &
Exercise 1
Open a new workbook and save it as Input Output 1.xlsm.
Then create a SUB called RevenueCalc that does the following:
(1) It asks the user for the unit price of some product and stores
it in the variable unitPrice, defined as Double type; (2) it asks
the user for the number of items sold and stores it in the variable
quantitySold, defined as Long type; (3) it calculates the revenue
from this product and stores it in the variable revenue, defined as
Double type; and (4) it displays a message such as “The revenue
from this product was $380.”
Exercise 2
Return to Exercise 1 and save your new program as
Input Output 2.xlsm. Start by using an input box to get the product’s
name. Then use input boxes to get the product’s unit price and the
quantity sold, and include the product’s name in the prompts for these
inputs. For example, a prompt might be “Enter the unit price for LaserJet
1100.” Next, calculate the revenue. Finally display a message that
contains all of the information, something like, “For the LaserJet 1100,
the unit price is $500, the quantity sold is 25, and the revenue is
$12,500.”
Interacting with the Spreadsheet
The following puts the string “Sales for March”
into Cell A1:
Range(“A1”).Value = “Sales for March”

The following puts the number 10 into each cell


in the range B2:D6:
Range(“B2:D6”).Value = 10

The following retrieves the value from a cell


and stores it in the string variable “title”:
Dim title as string
title = Range(“A1”).Value

Then to place “title” into Cell A8:


Range(“A8”).Value = title

To copy from A3:B4 to D3:E4 type:


Range(“A3:B4”).Copy Range(“D3:E4”)

To copy the value from A3:B4 to D6:E7 type:


Range(“D6:E7”).Value = Range(“A3:B4”).Value

Activation Button:
Insert a Button Form Control (under
Developer →Controls→Insert→Form Controls)
and select the SUB that you want the button
to activate (just like creating one for a
macro).
Exercise 3
The file Input Output 3_1.xlsx (on the course website) is a
template for calculating the total order cost for ordering a
product with quantity discounts. The table (range-named
LTable) in the range A4:C8 contains unit costs for various order
quantity intervals. The range B11:B13 contains a typical order
cost calculation, where the input is the order quantity in Cell
B11 and the ultimate output is the total cost in Cell B13. Take a
look at this file to see how a VLOOKUP function is used to
calculate the appropriate unit cost in Cell B12.

Write two SUBS called CreateTable and ClearTable, which


will eventually be attached to buttons. The CreateTable SUB
should prompt the user for three different order quantities. It
should then place these quantities, along with their
corresponding total costs, into Cells D12:E14. Basically, the
program will plug each potential order quantity into Cell B11
and then transfer the corresponding total cost from Cell B13 to
Column E of the table. The ClearTable button will simply erase
the entries created by CreateTable.
A B C D E F G H
1 Calculating ordering costs with quantity discounts
2
3 Lower limit Upper limit Unit cost
Create Table
4 0 499 $12.50
5 500 999 $12.25
6 1000 1999 $12.00
Clear Table
7 2000 3999 $11.50
8 4000 Unlimited $11.00
9
10 Basic calculation Table of total cost versus quantity ordered
11 Quanity ordered 5000 Quantity Total cost
12 Unit cost $11.00 100 $1,250
13 Total cost $55,000 2000 $23,000
14 5000 $55,000
15
Built-In Constants in VBA
Arrow Keys
xlDown, xlUp, xlToRight, and xlToLeft

Colors
vbBlack, vbBlue, vbCyan, vbGreen,
vbMagenta, vbRed , vbWhite, and vbYellow

Horizontal Alignment
xlRight, xlLeft, and xlCenter

Message Box Icons


 vbInformation
 vbExclamation
 vbQuestion
 vbCritical
Using Excel Functions in VBA
You can use certain regular Excel functions in
VBA code (not including the natural log, square
root, random number, Today(), and IF) by
preceding the function with:

WorksheetFunction.
As soon as you type the last period, a list of
most Excel functions appears from which you
can select.
Examples

A B C D E
1 6 4 2 8 10
2 74.8

WorksheetFunction.MAX(Range(“A1:E1”))
WorksheetFunction.SUM(Range(“A1:E1”))
WorksheetFunction.AVERAGE(Range(“A1:E5”))
WorksheetFunction.FLOOR(Range(“A2”),1)
WorksheetFunction.RANDBETWEEN(1,6)

The IF Function in VBA


The IIf function in VBA uses the same syntax
as the IF function in Excel (but ranges must be
specified with VBA syntax such as )
Warning: A few Excel functions are different
in VBA than in Excel. In particular:

Natural Logarithm of 20 = log(20), not LN(20)

Square Root of 20 = sqr(20), not SQRT(20)

Uniform (0, 1) Random Number = rnd, not RAND()

Today’s date = Date, not Today()

VBA’s Count property counts all cells (even empty


ones), while Excel’s “Count” function only counts cells
containing numbers.
String Functions
Left(string, n)—returns the first n characters of string
Example: Left(“Mr. Spock”, 5)
Result = “Mr. S”

Right(string, n)—returns the last n characters of string


Example: Right(“Vulcans Rule”, 4)
Result = “Rule”

Mid(string, n1, n2)—starting a character n1 of string, returns the first n2


characters
Example:
Mid(“Amok Time makes Vulcans crazy.”, 6, 18)
Result = “Time makes Vulcans”

Omitting n2 returns the rest of the string:


Mid(“Amok Time makes Vulcans crazy.”, 6)
Result = “Time makes Vulcans crazy.”

Len(string)—returns the number of characters in string


(spaces count)
Example:
Len(“Captain Picard rocks!”)
Result = 21

Replace(string, substring to replace, replace with)—replaces a portion


of a string with something new
Example:
Replace(“The month is Jan.”,“Jan.”,“Feb.”)
Result = “The month is Feb.”

StrReverse(string)—reverses the string


Example:
StrReverse(“Counselor Troy knows all.”)
Result = “.lla swonk yorT rolesnuoC”
User-Defined Functions
Excel provides a host of built-in functions.
However, sometimes programmers wish to create
their own functions for use in later applications,
rather than retyping the formula every time that
they want to make a specific calculation.

A function takes one or more arguments & returns


a value (into that cell or broader formula).

The code looks very similar to the code for a


SUB. As with SUBs:
Code is stored in a module. →Insert→Module
Start a Function
→Insert→Procedure [type in a name]
→[Click on Function]OK
(the name must be a single word)
Place the arguments [defined As Type between the ()]
Put As Type after the parenthesis (where type is the
variable type of the returned value)

Put all other commands between:


“Public Function name()” and
“End Function”
A function subroutine can be used in one of two
ways. It can be called by another SUB (or even
another function subroutine), or it can be used as a
new function in an Excel formula.

To make your function available in all future


workbooks, save it in your Personal.xlsb library
file.

Examples
1. Function for the maximum of two numbers

Public Function Larger(number1 As Double, number2 as Double) As Double


If number1 >= number2 Then
Larger = number1
Else
Larger = number2
End If
End Function

2. Function to take the first 5 characters from a name

Public Function Abb(name As String) As String


Abb = Left(name, 5)
End Function

3. Economic Order Quantity


Public Function EOQ(SetupCost as Double, Demand as Long, HoldingCost as Double) as Double

EOQ = SQR(2*SetupCost*Demand / HoldingCost)

End Function
Code for the Exercises
Exercise 1
Public Sub RevenueCalc()

Dim unitPrice As Double


Dim quantitySold As Long
Dim revenue As Double

unitPrice = InputBox("What is the unit price?", "Unit Price")


quantitySold = InputBox("How many units have been sold?", "Units Sold")
revenue = unitPrice * quantitySold
MsgBox "The revenue from this product was " & FormatCurrency(revenue, 0) & "."

End Sub

Exercise 2
Public Sub RevenueCalc2()

Dim productName As String


Dim unitPrice As Double
Dim quantitySold As Long
Dim revenue As Double

productName = InputBox("What is the name of the product?", "Product Name")


unitPrice = InputBox("What is the unit price of " & productName & "?", "Unit Price")
quantitySold = InputBox("How many units of " & productName & " have been sold?", _
"Units Sold")
revenue = unitPrice * quantitySold
MsgBox "For the " & productName & ", the unit price is " & FormatCurrency(unitPrice, 0) _
& ", the quantity sold is " & quantitySold & ", and the revenue is " _
& FormatCurrency(revenue, 0) & ".", vbInformation, "Results"

End Sub
Exercise 3
Public Sub Create()

Dim Q1 As Long
Dim Q2 As Long
Dim Q3 As Long
Q1 = InputBox("Enter the first order quantity.")
Q2 = InputBox("Enter the second order quantity.")
Q3 = InputBox("Enter the third order quantity.")
Range("B11").Value = Q1
Range("D12").Value = Q1
Range("E12").Value = Range("B13").Value
Range("B11").Value = Q2
Range("D13").Value = Q2
Range("E13").Value = Range("B13").Value
Range("B11").Value = Q3
Range("D14").Value = Q3
Range("E14").Value = Range("B13").Value
End Sub

Public Sub ClearTable()


Range("D12:E14").ClearContents
End Sub
Some Fundamental VBA Commands
<F2>
brings up the object browser
<F5>
runs a subroutine
<F8>
steps through a subroutine one line at a time
<Ctrl><F8>
runs a subroutine to the point of the cursor
<F9>
inserts a breakpoint into the code that pauses execution
Application.CutCopyMode = False
presses the Escape key when a selection is surrounded by a
dancing box after having pressed the copy button
Const name = value
defines a constant called name and sets it equal to value
(can be used for parameters that never change; the name does
not need to be defined with a Dim statement)
Dim variable name As type of variable
defines the variable variable name as type type of variable
FormatCurrency(value, #)
formats a number as currency formatting with # decimal places
Example: FormatCurrency(1500.67,1) displays $1,500.7
FormatNumber(value, #)
formats a number with commas and # decimal places
Example: FormatNumber(1500.67,1) displays 1,500.7
Range(rangename).ClearContents
erases contents in the range called rangename
vbNewLine (also vbCrLf)
inserts a carriage return (start on a new line) within a message
box [be sure to put an “&” sign before and after]
vbTab
inserts a tab within a message box [be sure to put an “&” sign
before and after]

You might also like