EIN 4905/ESI 6912 Decision Support Systems Excel

Download Report

Transcript EIN 4905/ESI 6912 Decision Support Systems Excel

Spreadsheet-Based Decision Support Systems
Chapter 14: Variables
Prof. Name
Position
University Name
[email protected]
(123) 456-7890
Overview







14.1 Introduction
14.2 Variable Declarations and Data Types
14.3 Variable Scope
14.4 Variables in User Interface
14.5 VBA Math Functions
14.6 Applications
14.7 Summary
2
Introduction

Declaring variables of different data types in VBA.

Private and public variables.

Using variables in the Message Box and Input Box user interfaces.

Mathematical, trigonometric, and derived math functions.

Conversion and string functions.

Two detailed examples of a simple DSS application which uses basic
Excel object manipulation, variables, and a simple user interface.
3
Variable Declarations and Data Types

Integer and Double

String

Boolean

Constant

Range

Worksheets

Object
4
Data Types

A data type categorizes the values that can be assigned to a variable.

There are several different data types available in VBA; we will focus on
the following seven data types for now, which we feel will be used most
often
–
–
–
–
–
–
–
Integer
Double
String
Boolean
Range
Worksheets
Object
5
Defining a Variable

To declare a variable in VBA, we use the command Dim
– Dim varaible As DataType

Remember that VBA for Excel is case-sensitive.

A constant variable is a variable whose value will never change.
– To declare a constant, we use Const
– Const variable = value

We will also see public and private declarations later.
6
Integers and Doubles

Both integers and doubles are numerical values.

Integers are non-decimal numbers ranging in value from -32,768 to
32,767.
– Integers will be used for simple numerical values, counting in loops, and
enumerating arrays.

Doubles have values from -1.79769E308 to -4.94065E-324 for negative
values and from 4.94065E-324 to 1.79769E308 for positive values.
– Doubles will be used for any data or calculations.
7
String

A string is a segment of text.

This text can include upper and lower-case letters, punctuation marks,
and numbers; however these numbers can not be used in calculations as
they will be viewed as text.
– We will use strings to name objects, label objects, and label data in
spreadsheets.
8
Boolean

A Boolean is a variable whose value is either True or False.
– We will use Boolean variables often in logic statements, If, Then statements,
and loops.
9
Range

A range is a variable which can be used with all of the properties and
methods of the Range object.


We must also use the Set declaration to initialize the value of a range
variable.
– For example, to set MyRange equal to cell A1 we would type the following.
Set MyRange = Range(“A1”)
10
Using Ranges

We will use Ranges often to increase the efficiency of our code.
– We can use ranges to define what we will call a StartCell.
– We set the value of this range variable at the beginning of our code and
reference this StartCell variable name throughout the remainder of the code.

We may also use Ranges to make our code more dynamic.
– We can use an Input Box to capture where the user wants to start a table.
Dim text As String, StartCell As Range
text = InputBox(“Enter starting cell for table:”)
Set StartCell = Range(text)
11
Worksheets

The worksheets data type defines a Worksheets object.

This variable can be assigned any of the properties or methods used with
the Worksheets object.
– We will use this object when creating loops and/or functions to perform
repeated methods or set repeated properties to multiple worksheets.
12
Object

The object variable can be used to define any object in Excel.

This can be considered a drawing object, a range, a worksheet, or any
other object.

Any of the properties or methods associated with any object in Excel can
be used with the object variable
13
Variable Scope

Private and Public Variable Declarations

Keeping Track of Variable Values
14
Variable Scope

It is important to understand the scope of each variable you declare.

You must check your code to see if a variable will be used in only one
sub procedure, or function procedure, or if it will be used in several
different procedures.

There are two types of variable declarations which determine the scope
of each variable.
– Public
– Private
15
Private Variables

A Private variable is declared using the Dim statement.

This variable can be private on two levels
– Procedure level = only used in the particular sub procedure in which it was
declared.
– Module level = used in any procedure in the module, but only in the particular
module in which it was declared.
16
Procedure Level vs Module Level

Procedure level private declaration
Sub Sub1()
Dim i As Integer
.....
End Sub
---------------------------------Sub Sub2()
Dim i As Integer
....
End Sub

Module level private declaration
Dim i As Integer
------------------------Sub Sub1()
.......
End Sub
-----------------------Sub Sub2()
........
End Sub
17
Public Variables

A Public variable on the other hand can be used in any sub procedure in
any module.

To declare a public variable, we use the Public statement.
– Public i As Integer
18
Keeping Track of Variable Values

There are two main ways to keep track of variable values while running
your program.
– Use the Watch Window
 Click on View > Watch Window from the menu
 Highlight any variable from the Code Window and drag it to the Watch Window
– Hold your cursor over a variable name in the Code Window to see a small
display of its value
19
Variables in User Interface

Message Box

Input Box
20
Message Box and Input Box

Message Boxes allow you to print something for the user to see in a
small dialog box.

Input Boxes allow you to prompt the user to enter some value in a small
dialog box.
21
Message Box

You can print the following with a Message Box
– Text
– Variable values
– Both using concatenation with & sign
MsgBox “This is a string of text.”
MsgBox "The height is " & h & vbCrLf & " and the width is " & w & "."
22
MsgBox Function

You can also use the MsgBox function to specify button types and
response types
– MsgBox (prompt, [buttons], [title], [helpfile, context])

The prompt is either the text or variable (or concatenation of both)
which will be displayed in the dialog box.

The title argument allows you to enter text a title for the dialog box.

The helpfile and context arguments allow you to give the user help
options.
23
MsgBox Function (cont’d)

The buttons argument takes a VB Constant value to determine the
number and style of buttons available to the user.
–
–
–
–

vbOKOnlyDisplays an OK button only
vbOKCancelDisplays OK and Cancel buttons
vbYesNoCancelDisplays Yes, No, and Cancel buttons
vbYesNoDisplays Yes and No buttons
You can also capture the user’s response to your Message Box with a
VBA variable called response.
–
–
–
–
–
–
–
vbOKIf response was OK
vbCancelIf response was Cancel
vbAbortIf response was Abort
vbRetryIf response was Retry
vbIgnoreIf response was Ignore
vbYesIf response was Yes
vbNoIf response was No
24
InputBox Function

The InputBox function is always assigned to a variable.

This function takes the following general form:
– InputBox (prompt, [title], [default], [xpos], [ypos], [helpfile, context])

The prompt and title arguments of the InputBox function are the same as
those of the MsgBox function.

The default argument allows you enter a default value to display in the
Input Box.

The xpos and ypos arguments allow you to position the Input Box
relative the left and top edges of the screen.

The helpfile and context arguments are the same as those of the
MsgBox function.
25
InputBox Function (cont’d)

For example, you may prompt the user to enter a number and store the
user value in the variable UserNumber.
UserNumber = InputBox (prompt, [title], [default], [xpos], [ypos], [helpfile,
context])
26
VBA Math Functions

Typical Math Functions

Trigonometric Functions

Derived Math Functions

Conversion Functions

String Functions
27
VBA Math Functions

We can use typical math functions in VBA without needing to create a
formula in the spreadsheet.

There are
– Typical Math Functions
– Trigonometric Functions
– Derived Math Functions
28
Typical Math Functions

We will describe six basic math functions
–
–
–
–
–
–
Abs
Sqr
Int
Rnd
Exp
Log
29
Abs Function

The Abs function calculates the absolute value of a variable.

This function can be used with both integer and double data types (as
well as with other numerical variables).

It will return the same data type which is used in the function.
– Abs(-10) = 10
30
Sqr Function

The Sqr function calculates the square root of a number.

It can also be used with any numerical data type (must be greater than
0).

It will always return a double data type.
– Sqr(100) = 10
31
Int Function

The Int function removes the decimal part of a double variable and
returns the integer part.

The result will be an integer data type.

For positive numbers, the Int function always rounds down.

For negative numbers, the Int function will return the first negative integer
less than or equal to the original variable value.
– Int(5.6) = 5
– Int(-4.3) = -5
32
Rnd Function

The Rnd function will generate a random number.

You can either enter a seed as a parameter for the function, or leave the
seed value blank.

This function will return a double data type between 0 and 1.

To create random integers in a specific range, use the formula
– Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
33
Exp Function

The Exp function raises the constant e to some power given in the
function statement.

The value returned will be a double data type.
– Exp(2) = e2 = 7.389056099
34
Log Function

The Log function calculates the natural log, that is the logarithm with
base e, of a given number.

The result is a double data type.

You can calculate logarithms with base n for any number by dividing the
natural logarithm of that number by the natural logarithm of n.

For example, to calculate the log of 15 with base 10 (Log1015), you
would type.
– Log(15) / Log(10) = 1.176091259
35
Trigonometric Functions

There are four basic trig functions that we will describe
–
–
–
–

Sin
Cos
Tan
Atn
These functions all take angles as a parameter, and this angle value
should be entered in radians.
– To convert degrees to radians, multiply degrees by pi/180
– To use the variable pi, we have to define a constant
Const pi = 3.14
36
Sin, Cos, and Tan Functions

The Sin, Cos, and Tan functions take an angle and return the ratio of
two sides of a right triangle.

The value returned is a double data type.

The result of the Sin and Cos functions will be between -1 and 1.
Sin(pi/4) = 0.7071067812
Cos(pi/3) = 0.5
Tan(pi/6) = 0.5773502692
37
Atn Function

The Atn function calculates the arctangent of a given ratio.

The result is an angle in radians, which will be a double data type.

The result of the Atn function will be between -pi/2 to pi/2 radians.
– To convert radians to degrees, multiply radians by 180/pi.
– Atn(0.5773502692) = pi/6
38
Derived Math Functions

Using the above functions, we can derive other functions.

There is a long list of examples of derived functions in Microsoft Visual
Basic Help; we will demonstrate two
– Arcsin
– Sec

We will use function procedures to create these and other derived math
functions.
39
Arcsin Function

We can derive the arcsine or inverse sine function using the Atn and Sqr
functions.

We can name this the Arcsin function.

This function would be defined as follows
– Arcsin(X) = Atn(X / Sqr(-X * X + 1))
40
Sec Function

We can derive the secant function using the Cos function.

We can name this function Sec.

It is defined as follows.
– Sec(X) = 1 / Cos(X)
41
Conversion Functions

There are several functions in VBA that can be used to convert one data
type to another.

Two main conversion functions used with numerical values are CInt and
CDbl.
– CInt converts a variable to an Integer data type:
 CInt(variable or expression)
– CDbl converts a variable to a Double data type:
 CDbl(variable or expression)

The Val function also extracts a numerical value from a string. The input
for this function is an expression.
– Val(expression)
42
Conversion Functions (cont’d)

Any numeric expression can also be converted to a string using the CStr
function. The input for this function is again any variable or expression:
– CStr(variable or expression)

the CDate function converts values into the Date data type. This data
type is necessary to work with dates in your code for comparisons or
calculations.
– CDate(variable or expression)

Two other useful conversion functions are Asc and Chr. These functions,
which use the ASCII list of numbers and characters, can be used to
convert letters to numbers and numbers to letters, respectively:
– Asc(character): Asc(“A”) = 65
– Chr(number): Chr(65) = “A”
43
String Functions

There are several string functions available in VBA.

Two useful string functions are UCase and LCase, which can be used to
convert a string into all upper case or all lower case, respectively.
– UCase(string variable or string expression)
– LCase(string variable or string expression)

To extract a segment from a string value, you can use the Mid function.
– Mid(string variable or string expression, starting_position, length)
 MidName = Mid(“JohnHenrySmith”, 5, 5)

Another useful string function is Len. This function determines the length
of a string variable value or string expression:
– Len(string variable or string expression)
44
Applications

Creating and Modifying Shapes

Making Calculations and Creating a Report
45
Applications (cont’d)

We consider two applications, or extended examples, in which we
implement some of the new techniques learned in this chapter.
– Creating and Modifying Shapes (Example 1)
 Message Boxes, Input Boxes, and some various data types
– Making Calculations and Creating Reports (Example 2)
 Several different functions and the range data type
46
Creating and Modifying Shapes

Let us create a program in which a user can
–
–
–
–
–
create either a square or a circle
label their shape
position their shape on the spreadsheet
keep track of how many squares and circles have been created
delete a square or circle
47
Figure 14.1


We begin by preparing the following spreadsheet.
We have a brief description of the program, and several buttons.
48
Creating a Square

To do this, we will first declare variables that can be assigned to an Input
Boxes to find the desired width and height of the square.

We call these variables width and height
– Both of these variables should be define as double data types
Sub CreateSquare()
Dim width As Double, height As Doulbe
width = InputBox("Please enter the width of your square:",
"Width", 50)
height = InputBox("Please enter the height of your
square:", "Height", 50)
End Sub
49
Creating a Square (cont)

Now we use the AddShape method associated with the ActiveSheet and
Shapes objects to create the square.
– The shape type parameter should be msoShapeRectangle
– The position parameters can be anything for now
– The width and height parameters will be set as our variable values
ActiveSheet.Shapes.AddShape(msoShapeRectangle, 146.25, 289.5, width,
height).Select

We then simply display a Message Box which tells the user that the
macro has run successfully and the square has been created.
50
Figures 14.2 and 14.3

The final procedure and output are as follows:
51
Creating a Circle



This sub procedure will be very similar to creating a square.
We only need to change the msoAutoShapeType to msoShapeOval.
However, we also decide to create a new variable, radius, to be used
for both the width and height values in the AddShape method.
Sub CreateCircle()
Dim radius As Double
radius = InputBox("Please enter the radius of your circle:",
“Radius", 50)
ActiveSheet.Shapes.AddShape(msoShapeOval, 146.25,
289.5, radius, radius).Select
MsgBox “Your circle has been created.”
End Sub
52
Figures 14.4 and 14.5

The final procedure and output are as follows:
53
Counting the Shapes

We will first need two variables (which can both be integer data types):
– NumSquares
– NumCircles

We first need to initialize these variables to have value 0.
– We cannot perform this initialization in either the CreateSquare() or
CreateCircle() sub procedures since we want to increase these values each
time the macros are called.
– Therefore, we can either create a new sub procedure called Main() or
Initialize() and assign it to a new “Start” button, or we can use the
Workbook_Open() event procedure.
– For now we use the Workbook event procedure.
54
Figures 14.6

The Public declaration of NumSquares and NumCircles.
55
Workbook Event Procedure




We create a Workbook_Open() event procedure in the Workbook object
of our current VBA project.
In this procedure we initialize the NumSquares and NumCircles variables
to be 0.
Since we want to use these variables in the Workbook object and in our
main module, we must declare them as public variables with the Public
statement.
We also clear the range of cells where the shapes will most likely be
created and/or positioned in this event procedure.
– We assume this range is A12:K50. We specify that this range is in our first
worksheet and use the Delete method.
56
Figure 14.7 and 14.8

The code is as follows:

We can now create and count objects:
57
Incrementing Variable Values

To increment a variable value in VBA, use the structure
– variable = variable + 1

We create two procedures for deleting squares and circles:
58
Label Shape


To label our shape, we first prompt the user to see what text will be used
as the label.
We declare a private variable called text and assign it to an Input Box as
follows
– text = InputBox("Please enter label for your shape:", "Shape Label", "Square
1")

Now we use the Selection object with the Characters property and Text
sub property and assign the value equal to our text variable.
– Selection.Characters.Text = text
59
Figures 14.10 and 14.11

The procedure and result:
60
Position Shape

To position a shape, instead of asking the user to provide two numerical
values for the left and top arguments of the AddShape method, we will
cut and paste the selected object to a specified range.

We first declare a private variable called position to capture the range
name where the user wants to move the selected object.

We then use a range variable called place to use this range value in our
Paste method.
61
Position Shape (cont)

The variable declarations, InputBox function, and range assignment
are written as follows
Dim position As String, place As Range
position = InputBox("Please enter cell name where you would like to
position your shape (below A12):", "Position", "A12")
Set place = Range(position)


We now use the Cut method on the Selection object, and then use the
ActiveSheet object and Paste method to paste the object to the desired
range.
We specify this range with the Destination argument as shown below.
– ActiveSheet.Paste Destination:=place
62
Figures 14.12 and 14.13

Positioning the shape in cell A12.
63
Making Calculations and Creating a Report

We will create a program which can make various calculations and
create reports.
– The user can generate a random numbers in a specified interval and
calculate its





absolute value
Integer value
square root
exponential power
natural logarithm
– The user can also provide an angle to calculate its
 Sine
 Cosine
 Tangent
– We also provide a “Clear All” button to clear current reports.
64
Figure 14.14


Our spreadsheet is prepared with the appropriate buttons and table
headings.
We only need three sub procedures for this program.
– CalcRandNum(), CalcAngles(), and ClearAll()
65
Random Number Calculations



We will first ask the user to specify an interval in which they want the
random number to be generated.
We will use two variables and the InputBox function to achieve this.
We declare these variables privately in the CalcRandNum() sub
procedure and name them low and upp.
low = InputBox("Please enter the lower bound of the interval in which you would
like to generate a random number: ", "Lower Bound", -10)
upp = InputBox("Please enter the upper bound of the interval in which you
would like to generate a random number: ", "Upper Bound", 10)
66
Rand Num Calc (cont)

We now use the following function to generate a random number in this
interval
– x = (upp - low + 1) * Rnd() + low

We will define this x variable publicly as we will use it to perform
calculations in our CalcAngles() sub procedure as well.
67
Rand Num Calc (cont)




We can insert this result into the first column of our random number
calculation table.
Since we will be inserting all other random number calculations into the
same table, we will use a range variable, similar to the StartCell example,
for this table and use it to reference all report values.
We define this range variable publicly as we will use it in the ClearAll()
procedure as well.
We name this variable RandStart and declare it as follows.
– Public RandStart As Range
68
Rand Num Calc (cont)

Now we should set this variable to a particular range in the worksheet.
We do this in the CalcRandNum() sub procedure by typing.
– Set RandStart = Worksheets(“Example 2”).Range(“A14”)

We can now use this variable as a Range object and apply the Offset
method to insert calculation results into our table. We insert the first
value, the random number generated in the specified interval, into the
first column.
– RandStart.Offset(1, 0).Value = x
69
Figures 14.15 and 14.16

We can now use the Value property of our range variable to insert all
other calculations directly.
70
Angle Calculation

For the CalcAngles() sub procedure we will begin by asking the user to
enter an angle in degrees.

We do this using the InputBox function again with the prompt, title, and
default value defined as shown below.
– x = InputBox("Enter an angle value in degrees:", "Angle value", 45)

Notice we used the same x value as before, which was declared as a
public variable.
71
Angle Calc (cont)

We now need to convert this value into radians before using any
trigonometric calculations.

To do this, we will first need to declare the constant pi.
– Const pi = 3.14

We can now use the following function to make the angle conversion.
– x = x * pi / 180
72
Angle Calc (cont)

We will use another range variable in this procedure to insert calculation
values into the angle calculation table.

We also define this variable publicly so that we can use it again in the
ClearAll() procedure.

We name this variable AngleStart and declare it as follows.
– Public AngleStart As Range
73
Figures 14.17 and 14.18

We can now use the Offset method again to insert the original degree
value of the angle, the converted radian value of the angle, and the Sin,
Cos, and Tan calculation results into the report.
74
Clear All Procedure

The last procedure to write is the ClearAll() sub procedure.

This procedure will simply clear the values in both tables.

We will use the ClearContents method so as to keep the borders and
other formatting of our table.

We will only clear the second row of both tables.


To do this, we will use the RandStart and AngleStart variables to define
the ranges we want to clear.
75
Clear All (cont)

To clear the second row of the random number calculation table.
– Range(RandStart.Offset(1, 0), RandStart.Offset (1, 5)).ClearContents

To clear the second row of the angle calculation table.
– Range(AngleStart.Offset(1, 0), AngleStart.Offset (1, 4)).ClearContents
76
Summary





To declare a variable in VBA, use the command Dim. It is important to
remember that VBA for Excel is case-sensitive.
There are several data types available for variables in VBA, including
integer, double, string, Booleans, range, worksheet, and object.
There are two types of variable declarations: Public and Private.
Message Boxes and Input Boxes allow us to communicate with the user
using VBA code. A Message Box prints information to a small dialog box,
and an Input Box prompts the user to enter information into a small
dialog box.
There are several math functions in VBA that can be used with variables
or values. There are a few trigonometric functions in VBA that you can
use with variables or values. You can also derive other functions using
the pre-defined VBA functions. There are also several conversion and
string functions in VBA.
77
Additional Links

(place links here)
78