vba & excel-mvo
TRANSCRIPT
-
7/28/2019 Vba & Excel-mvo
1/35
VBA & Excel.ppt 1
Primer on VBA & Excel for
Discrete-Event Simulation
See also IOE574-startup.xls
http://www.engin.umich.edu/class/ioe574/IOE574-startup.xlshttp://www.engin.umich.edu/class/ioe574/IOE574-startup.xlshttp://www.engin.umich.edu/class/ioe574/IOE574-startup.xlshttp://www.engin.umich.edu/class/ioe574/IOE574-startup.xls -
7/28/2019 Vba & Excel-mvo
2/35
VBA & Excel.ppt 2
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
-
7/28/2019 Vba & Excel-mvo
3/35
VBA & Excel.ppt 3
VBA & Excel for Discrete-EventSimulation
Advantages VBA is a full-featured programming language
You have access to Excel functions for
computation and Excel for storing andanalyzing outputs including USERINTERACTION!
Disadvantages VBA is interpreted, not compiled, so execution
is slow (can be overcome by compiling VB)
Excel functions can be buggy
-
7/28/2019 Vba & Excel-mvo
4/35
VBA & Excel.ppt 4
Accessing VBA in Excel
Tools Macros Visual Basic Editor
Enter VBA through the navigation buttonsin the top toolbars
VBA DesignMode
Visual BasicEditor
Design mode is the time
during which no code fromthe project is running andevents from Excel or yourproject will not execute.
-
7/28/2019 Vba & Excel-mvo
5/35
VBA & Excel.ppt 5
VB Edit Window
Project
Explorer
PropertyInspector
Code Window
-
7/28/2019 Vba & Excel-mvo
6/35
VBA & Excel.ppt 6
Structure of VBA Project
Modules are collections of VBA code
Procedures (Subroutines - Subs) andFunctions
Declarations come before any Subs orFunctions that are global to the Module
UserForms are graphic objects for user
input and output; we will not have to workwith UserForms
-
7/28/2019 Vba & Excel-mvo
7/35
VBA & Excel.ppt 7
Variables
Declare byDim varname As Type
Better to use Data Types:Dim amount AsDouble note double precision is useful for us!
Dim yearAsIntegerDim name AsString
Other data types: Boolean, Byte, Currency,Date
Default (no type) is Variant Option Explicit forces all variables to be
declared
-
7/28/2019 Vba & Excel-mvo
8/35
VBA & Excel.ppt 8
Variables(contd.)
Can declare type by appending a symbol:% - integer & - long integer! - single # - double@ currency $ - string
Can modify scope (outside Subs & Fcns)
Private L AsInteger(only current module)
Public billsPaid AsCurrency(available to any module)
-
7/28/2019 Vba & Excel-mvo
9/35
VBA & Excel.ppt 9
Constants & Statics
[Public|Private] Const constantName [Astype] = expression Value cannot be changed
PublicConst PI = 3.1, NumPLANETS = 9 Oops, make that 8 as of August 2006!
Static causes variables in Subs and
Functions to retain their values (normallylost when you exit Sub or Function) Static yourName AsString
-
7/28/2019 Vba & Excel-mvo
10/35
VBA & Excel.ppt 10
Arrays
Dim vect(1 to 100) as IntegerDim Elf(0 to 5, 0 to 20) as String
You can also dynamically allocate andreallocate an array
Dim Calendar() as Integer
ReDim Calendar (1 to 31) as Integer
-
7/28/2019 Vba & Excel-mvo
11/35
VBA & Excel.ppt 11
Control Structures
Decisions
IfanyDate < Now Then
anyDate = NowEndIf
Next, consider If Then Else
-
7/28/2019 Vba & Excel-mvo
12/35
VBA & Excel.ppt 12
Decisions(contd.)
IfIndex = 0 ThenX = X + 1Y = VBA.Sqr(X)
ElseIfIndex = 1 ThenY = VBA.Sqr(X)
ElseIfIndex = 2 ThenY = X
ElseX = 0EndIf
-
7/28/2019 Vba & Excel-mvo
13/35
VBA & Excel.ppt 13
Decisions(contd.)
SelectCase IndexVariable
Case 0
statements
Case 1 to 10
statementsCase Is < 0
statements
CaseNumSteps
statementsCaseElse
statements
EndSelect
Notice that the cases
can be constants, ranges,conditions and variables;this is a powerful controlstructure that we will useto select events to execute
-
7/28/2019 Vba & Excel-mvo
14/35
VBA & Excel.ppt 14
Loops/Iterations
Do {While|Until}conditionstatements
Loop
-------------------------------------------
Do statementsLoop {While|Until}condition
-
7/28/2019 Vba & Excel-mvo
15/35
VBA & Excel.ppt 15
Loops(contd.)
Forcounter = start To end [Step increment]statements
Next counter
--------------------------------
ForEach element In groupstatements
Next element
-
7/28/2019 Vba & Excel-mvo
16/35
VBA & Excel.ppt 16
Exiting Control Structures
ForJ = 1 To 10 Step 2[statement block]ExitFor[statement block]
Next J-----------------------Do
[statement block]ExitDo[statement block]
Loop Until Check = False
Optional statements to
allow early exit from theloop before thetermination condition
-
7/28/2019 Vba & Excel-mvo
17/35
VBA & Excel.ppt 17
Exit Command Details
Exit Do Provides a way to exit a Do...Loop statement. It can be used onlyinside a Do...Loop statement. Exit Do transfers control to the statementfollowing the Loop statement. When used within nested Do...Loopstatements, Exit Do transfers control to the loop that is one nested levelabove the loop where ExitDo occurs.
Exit ForProvides a way to exit a Forloop. It can be used only in a For...NextorForEach...Next loop. Exit Fortransfers control to the statementfollowing the Next statement. When used within nested Forloops, Exit Fortransfers control to the loop that is one nested level above the loop whereExit Foroccurs.
Exit Function Immediately exits the Functionprocedure in which it
appears. Execution continues with the statement following the statementthat called the Function.
Exit Sub Immediately exits the Sub procedure in which it appears.Execution continues with the statement following the statement that calledthe Sub procedure.
http://hhobj_4.click%28%29/http://hhobj_5.click%28%29/http://hhobj_5.click%28%29/http://hhobj_4.click%28%29/ -
7/28/2019 Vba & Excel-mvo
18/35
VBA & Excel.ppt 18
Code Modules
Excel Objects (ThisWorkbook, Sheet#)
Modules
Typically we put our code here
A Module is a collection of Subs andFunctions
Insert Module
More: Class Modules (see master used for simlib)
User Forms
-
7/28/2019 Vba & Excel-mvo
19/35
VBA & Excel.ppt 19
Procedures
Sub name(arguments) (i.e., subroutine) no value returned in the sense of a function, but
variables are modified.
Called as needed via
Call mySub(param1, param2)
Function name(arguments) AS type (i.e., function)
value returned assign return value to function name: e.g.,
X = myFunction(2, 7, Z)
-
7/28/2019 Vba & Excel-mvo
20/35
VBA & Excel.ppt 20
Subs can also have Public or Private scope(default is Public)Public Sub MM1_main() this is a common way to begin
a sub that is public and all variables to becommunicated to the routine calling it are public.
Basic syntax{Public|Private} Sub name(arguments)
[statements]
Exit Sub[statements]End Sub
Subs
Optional way to leave the Subbefore reaching the End statement
-
7/28/2019 Vba & Excel-mvo
21/35
VBA & Excel.ppt 21
Functions
Functions can also have Public or Privatescope (default is Public)Public Function Timer() As String e.g., Timer returned
as Failure
Basic syntax
{Public|Private} Function fname(arguments) AS type[statements]fname = valuExit Function[statements]
End Function Optional way to leave the Functionbefore reaching the End statement
Fname returned to modulewith value valu
-
7/28/2019 Vba & Excel-mvo
22/35
VBA & Excel.ppt 22
Pass by Reference (default) means thatchanges to the value of the variable will bereturned
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 priceas Integer)
Arguments for Procedures
-
7/28/2019 Vba & Excel-mvo
23/35
VBA & Excel.ppt 23
Some Useful Code for Interactingwith Excel
The following are some pieces of codethat are useful for doing VBA with Excel.
See the code on the course web site forother examples.
Basic_Simulation_Modeling.xls
IOE574-startup.xls
others yet to come.
http://www.engin.umich.edu/class/ioe574/r/Basic_Simulation_Modeling.xlshttp://www.engin.umich.edu/class/ioe574/IOE574-startup.xlshttp://www.engin.umich.edu/class/ioe574/IOE574-startup.xlshttp://www.engin.umich.edu/class/ioe574/IOE574-startup.xlshttp://www.engin.umich.edu/class/ioe574/IOE574-startup.xlshttp://www.engin.umich.edu/class/ioe574/r/Basic_Simulation_Modeling.xls -
7/28/2019 Vba & Excel-mvo
24/35
VBA & Excel.ppt 24
This is how you addressVBA intrinsic functions
Writing to a Sheet
Put the absolute value of the variableFudge in row 2 (or I), column 20 (or J) ofthe 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
-
7/28/2019 Vba & Excel-mvo
25/35
VBA & Excel.ppt 25
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 5Range("1:1,3:3,8:8") Rows 1, 3, and 8
Range("A:A,C:C,F:F") Columns A, C, and F
-
7/28/2019 Vba & Excel-mvo
26/35
VBA & Excel.ppt 26
Reading from a Worksheet
To read in a value, use the .Value method,applying the same ideas used for writing:
X = Worksheets(mySheet).Range(T2).Value
note: T = column 20, so T2 is col. 20, row2
Excel likes the (column, row) order ratherthan (row, column) when using Range
-
7/28/2019 Vba & Excel-mvo
27/35
VBA & Excel.ppt 27
Use an Excel Function
VBA has a limited number of built-infunctions, but you can access the plethoraof Excel worksheet functions.
This example uses the Excel Max function
W = WorksheetFunction.Max(0, W + S - a)
-
7/28/2019 Vba & Excel-mvo
28/35
VBA & Excel.ppt 28
Running the Code
Your modules will as appear as Macrosthat can be run from Excel under
Tools Macro Macros dialogue-box Perhaps the easiest way to run the code is
to place your cursor in the module youwant to run and press theRun Sub/UserForm button. (there is agreen play button on the toolbar, too)
-
7/28/2019 Vba & Excel-mvo
29/35
VBA & Excel.ppt 29
DebuggingUseful tools in theDebug menu
Setting break pointscauses code to stopwhen the point is reached(F5 to continue)
Passing the cursor
over variablesshows their currentvalue
-
7/28/2019 Vba & Excel-mvo
30/35
VBA & Excel.ppt 30
Dim Clock As Double ' simulation clockDim NextFailure As Double ' time of next failure eventDim NextRepair As Double ' time of next repair eventDim S As Double ' system stateDim Tlast As Double ' time of previous eventDim Area As Double ' area under S curve
Public Function Timer() As String
' Determine the next event and advance timeIf NextFailure < NextRepair ThenTimer = "Failure"Clock = NextFailureNextFailure = 1000000
Else
Timer = "Repair"Clock = NextRepairNextRepair = 1000000
End IfEnd Function
These variablesare global since
they are declaredbefore any Subor Function
Notice that Function must
be typed
Value "Failure" is returnedas Timer, the name of the
function.
An apostrophe indicates a commentDiscrete TTF EXAMPLE
-
7/28/2019 Vba & Excel-mvo
31/35
VBA & Excel.ppt 31
Public Sub MainProgram()' Program to generate a sample path for the reliability example
Dim NextEvent As String
S = 2Clock = 0Tlast = 0
Area = 0NextFailure = WorksheetFunction.Floor(6 * Rnd(), 1) + 1NextRepair = 1000000
Do Until S = 0NextEvent = TimerSelect Case NextEventCase "Failure"
Call FailureCase "Repair"
Call RepairEnd Select
LoopMsgBox ("System failure at time " _
& Clock & " with average # components " & Area / Clock)End Sub
NextEvent is local to this Sub since itis declared within the Sub
Note use of an Excel function
A Do Until loop and a Select Casestatement
-
7/28/2019 Vba & Excel-mvo
32/35
VBA & Excel.ppt 32
Public Sub Failure()'Failure event
Area = Area + (Clock - Tlast) * STlast = Clock
S = S - 1If S = 1 ThenNextFailure = Clock +
WorksheetFunction.Floor(6 * Rnd(), 1) + 1
NextRepair = Clock + 2.5End If
End Sub
P bli S b R i ()
-
7/28/2019 Vba & Excel-mvo
33/35
VBA & Excel.ppt 33
Public Sub Repair()'Repair event
Area = Area + (Clock - Tlast) * S
Tlast = Clock
S = S + 1If S = 1 Then
NextRepair = Clock + 2.5NextFailure = Clock +
WorksheetFunction.Floor(6 * Rnd(), 1) + 1End If
End Sub
-
7/28/2019 Vba & Excel-mvo
34/35
VBA & Excel.ppt 34
Finishing Up
Exercise: Write a Sub that inserts aworksheet named Count into the
Workbook, then writes the numbers
1,2,,10 in the first row, the first tencolumns. Use a loop to do this.
-
7/28/2019 Vba & Excel-mvo
35/35
VBA & Excel ppt 35
Finding/Creating a SheetDim found As Boolean
Dim sheetNext As Worksheet' Set up mySheet sheet for output
found = FalseFor Each sheetNext In Worksheets
If sheetNext.Name = mySheet" Then
found = TrueExit ForEnd If
Next sheetNext
If found = True ThenWorksheets(mySheet").Select
ActiveSheet.UsedRange.ClearElse
Worksheets.AddActiveSheet.Name = mySheet"
End If
FYIuseful sol. To exercise