Sie sind auf Seite 1von 32

kkkkkkkkkkkkkkkkkkkkkkkkkkl

kkl

VBA & Excel.ppt 1


Visual Basic for Applications
• VBA a significant subset of the stand-
alone Visual Basic programming language
• It is integrated into Microsoft Office
applications (and others, like Arena)
• It is the macro language of Excel
• You can add
– Forms for dialog boxes with user input
– Classes for object definitions
– Modules containing procedures
VBA & Excel.ppt 2
VBA & Excel for Discrete-Event
Simulation
• Advantages
– VBA is a full-featured programming language
– You have access to Excel functions for
computation and Excel for storing and
analyzing outputs – including USER
INTERACTION!
• Disadvantages
– VBA is interpreted, not compiled, so execution
is slow (can be overcome by compiling VB)
– Excel functions can be buggy
VBA & Excel.ppt 3
Accessing VBA in Excel
• Tools  Macros  Visual Basic Editor
• Enter VBA through the navigation buttons
in the top toolbars
“Design mode” is the time
during which no code from
the project is running and
events from Excel or your
project will not execute.

Visual Basic VBA Design


Editor Mode

VBA & Excel.ppt 4


Project Explorer
VB Edit Window

Code Window
Property Inspector

VBA & Excel.ppt 5


Structure of VBA Project
• Modules are collections of VBA code
– Procedures (Subs) and Functions
– Declarations before any Subs or Functions
that are global to the Module
• UserForms are graphic objects for user
input and output; we will not work with
UserForms

VBA & Excel.ppt 6


Variables
• Declare by Dim
• Better to use Data Types:
Dim amount As Double
Dim year As Integer
Dim name As String
• Other data types: Boolean, Byte, Currency,
Date
• Default (no type) is Variant
• Option Explicit forces all variables to be
declared

VBA & Excel.ppt 7


Variables(cont’d.)
• Can declare type by appending a symbol:
% - integer & - long integer
! - single # - double
@ currency $ - string

• Can modify scope (outside Subs & Fcns)


– Private L As Integer
(only current module)
– Public billsPaid As Currency
(available to any module)

VBA & Excel.ppt 8


Constants & Statics
• [Public|Private] Const constantName [As
type] = expression
– Value cannot be changed
– Public Const PI = 3.1, NumPLANETS = 9
• Static causes variables in Subs and
Functions to retain their values (normally
lost when you exit Sub or Function)
– Static yourName As String

VBA & Excel.ppt 9


Arrays
• Dim vect(1 to 100) as Integer
Dim Elf(0 to 5, 0 to 20) as String

• You can also dynamically allocate and


reallocate an array

Dim Calendar() as Integer

ReDim Calendar (1 to 31) as Integer

VBA & Excel.ppt 10


Control Structures
• Decisions

If anyDate < Now Then


anyDate = Now
End If

Next, consider If … Then … Else

VBA & Excel.ppt 11


Decisions(cont’d.)
If Index = 0 Then
X=X+1
Y = VBA.Sqr(X)
Else If Index = 1 Then
Y = VBA.Sqr(X)
Else If Index = 2 Then
Y=X
Else
X=0
End If
VBA & Excel.ppt 12
Decisions(cont’d.)
Select Case IndexVariable
Case 0
statements…
Case 1 to 10 Notice that the “cases”
statements… can be constants, ranges,
conditions and variables;
Case Is < 0 this is a powerful control
statements… structure that we will use
Case NumSteps to select events to execute
statements…
Case Else
statements…
End Select
VBA & Excel.ppt 13
Loops/Iterations
Do {While|Until} …condition
statements…
Loop

-------------------------------------------

Do
statements…
Loop {While|Until} …condition
VBA & Excel.ppt 14
Loops(cont’d.)
For counter = start To end [Step increment]
…statements
Next counter

--------------------------------

For Each element In group


…statements
Next element
VBA & Excel.ppt 15
Exiting Control Structures
For J = 1 To 10 Step 2
[statement block]
Exit For
[statement block] Optional statements to
allow early, graceful exit
Next J from the loop before the
----------------------- termination condition

Do
[statement block]
Exit Do
[statement block]
Loop Until Check = False
VBA & Excel.ppt 16
Code Modules
• Excel Objects (ThisWorkbook, Sheet#)
• Modules
– Typically we put our code here
– A Module is a collection of Subs and
Functions
– Insert  Module
• More:
– Class Modules (see “master” used for simlib)
– User Forms
VBA & Excel.ppt 17
Procedures
• Sub (routines)
– no value returned
– Called when needed
Call mySub(param1, param2)
• Function
– value returned
– assign return value to function name
X = myFunction(2, 7, Z)

VBA & Excel.ppt 18


Subs
• Subs can also have Public or Private
scope (default is Public)
• Basic syntax
{Public|Private} Sub name(arguments)
statements…
Optional way to leave the Sub
Exit Sub before reaching the End statement
statements…
End Sub

VBA & Excel.ppt 19


Functions
• Functions can also have Public or Private
scope (default is Public)
• Basic syntax

{Public|Private} Function name(arguments) AS type


statements…
Value returned as the name
name = return value of the function
Exit Function
statements…
End Function Optional way to leave the Function
before reaching the End statement

VBA & Excel.ppt 20


Arguments for Procedures
• Pass by Reference (default) means that
changes to the value of the variable will be
returned

Sub stuff(item As String, price as Integer)

• Pass by Value means only the value is


passed so the original variable is unchanged

Sub stuff(ByVal item As String, ByVal price as


Integer)
VBA & Excel.ppt 21
Some Useful Code for Interacting
with Excel
• The following are some pieces of code
that are useful for doing VBA with Excel.
• See the code on the course web site for
other examples.

VBA & Excel.ppt 22


FYI –useful for exercise at end

Finding/Creating a Sheet
Dim found As Boolean
Dim sheetNext As Worksheet
' Set up mySheet sheet for output

found = False
For Each sheetNext In Worksheets
If sheetNext.Name = “mySheet" Then
found = True
Exit For
End If
Next sheetNext

If found = True Then


Worksheets(“mySheet").Select
ActiveSheet.UsedRange.Clear
Else
Worksheets.Add
ActiveSheet.Name = “mySheet"
End If

VBA & Excel.ppt 23


Writing to a Sheet
• Put the absolute value of the variable
Fudge in row 2 (or I), column 20 (or J) of
the Worksheet named mySheet.

Worksheets(“mySheet”).Cells(2,20) = VBA.Abs(Fudge)

Worksheets(“mySheet”).Cells(I,J) = VBA.Abs(Fudge)

Worksheets(“mySheet”).Range(“T2”)=VBA.Abs(Fudge)
Range is general – see next page This is how you address
VBA intrinsic functions
VBA & Excel.ppt 24
Ways to use .Range Method
Range("A1") Cell A1
Range("A1:B5") Cells A1 through B5
Range("C5:D9,G9:H16") A multiple-area selection

Range("A:A") Column A
Range("1:1") Row 1
Range("A:C") Columns A through C
Range("1:5") Rows 1 through 5

Range("1:1,3:3,8:8") Rows 1, 3, and 8

Range("A:A,C:C,F:F") Columns A, C, and F

VBA & Excel.ppt 25


Reading from a Worksheet
• To do this you use the .Value method,
applying the same ideas used for writing:

X = Worksheets(“mySheet”).Range(“T2”).Value

note: t = column 20
Excel likes the (column, row) order rather
than (row, column)

VBA & Excel.ppt 26


Use an Excel Function
• VBA has a limited number of built-in
functions, but you can access any Excel
worksheet function.
• This example uses the Excel Max function

W = WorksheetFunction.Max(0, W + S - a)

VBA & Excel.ppt 27


Running the Code
• Your modules will as appear as Macros
that can be run from Excel under

Tools  Macros  Macros…


• Perhaps the easiest way to run the code is
to place your cursor in the module you
want to run and press the
Run Sub/UserForm button. (there is a
green play button on the toolbar, too)

VBA & Excel.ppt 28


Useful tools in the
Debug menu Debugging

Setting break points


causes code to stop
when the point is reached
(F5 to continue)

Passing the cursor


over variables
shows their current
value

VBA & Excel.ppt 29


IN-CLASS EXAMPLE An apostrophe indicates a comment

Dim Clock As Double ' simulation clock These variables


Dim NextFailure As Double ' time of next failure event are global since
Dim NextRepair As Double ' time of next repair event they are declared
Dim S As Double ' system state before any Sub
Dim Tlast As Double ' time of previous event or Function
Dim Area As Double ' area under S curve

Public Function Timer() As String Notice that Function must


' Determine the next event and advance time be typed
If NextFailure < NextRepair Then
Timer = "Failure"
Clock = NextFailure
NextFailure = 1000000 Value is returned as the
Else name of the function
Timer = "Repair"
Clock = NextRepair
NextRepair = 1000000
End If
End Function

VBA & Excel.ppt 30


Public Sub MainProgram()
' Program to generate a sample path for the reliability example
Dim NextEvent As String
NextEvent is local to this Sub since it
S=2 is declared within the Sub
Clock = 0
Tlast = 0
Area = 0
NextFailure = WorksheetFunction.Floor(6 * Rnd(), 1) + 1
NextRepair = 1000000

Do Until S = 0 Note use of an Excel function


NextEvent = Timer
Select Case NextEvent
Case "Failure"
Call Failure
An Until loop and a Select Case
Case "Repair" statement
Call Repair
End Select
Loop
MsgBox ("System failure at time " _
& Clock & " with average # components " & Area / Clock)
End Sub
VBA & Excel.ppt 31
Finishing Up
• Exercise: Write a Sub that inserts a
worksheet named “Count” into the
Workbook, then writes the numbers
1,2,…,10 in the first row, the first ten
columns. Use a loop to do this.

VBA & Excel.ppt 32