powerpoint presentationekwhite/geen1300sum2010/lecture-6...to cell a1 . 6/14/2010 3 9 ... there is...
Post on 13-Apr-2018
219 Views
Preview:
TRANSCRIPT
6/14/2010
1
1
VBA program units: Subroutines and Functions
Subs:
•a chunk of VBA code that can be executed by running
it from Excel, from the VBE, or by being “called” by
another VBA subprogram
•may have zero-to-several arguments that provide
for values to be input to or output from the Sub
•can be created with the macro recorder or typed
in from scratch
Sub name (optional arguments)
End Sub 2
•functions can return values
•a VBA subprogram that can be executed by using its name
in a VBA expression or an Excel formula
Functions:
•functions cannot be recorded, but must be typed into the VBE
•functions may have zero-to-several input arguments
Function name (optional arguments)
End Function
3
Examples:
Function Twice(mynumber)
Twice = 2*mynumber
End Function
Sub hello()
MsgBox ("Hello") „ MsgBox “Hello” would work here
too
End Sub
4
Examples:
Function Icy(temp)
If (temp <= 32) Then MsgBox ("Yes")
Icy = temp
End Function
6/14/2010
2
5
When you write VBA code, it is possible to “get away” without
declaring the data types of variables that you use.
But, this is bad programming practice, so it is best to declare
the “types” of all variables used in VBA:
Dim <variable-name> As <type>
This requirement is enforced by putting the Option Explicit
statement at the top of every VBA module you develop.
“Declaring” variables
6
Making VBA work
Save As Macro-Enabled workbook (.xlsm)
Make sure Options -> Trust Settings is allowing macros
Make a new directory for each VBA/Excel workbook (clarity)
Functions: test by calling in Excel worksheet (or from Sub)
Allowed to return values
Multiple arguments possible
Subs: test by running with F8 in VBE
Allowed to change cells
Multiple arguments possible
Check settings by loading Kick Calculator; should run!
7
Enforcing variable declaration
put Option Explicit statement at the top of every module
or
set VBE‟s Tools Options
Require Variable Declaration
and VBE will do it for you!
8
Object-oriented programming
Objects : entities that have attributes (“properties”) that can
be manipulated
These are generally organized
in hierarchies:
Microsoft Office
Word
Excel
“Application” Objects
in red
Selection
The object
that
corresponds
to cell A1
6/14/2010
3
9
Object Collections
Workbooks all currently-open workbook objects
Charts all charts contained in a particular workbook
Worksheets all sheets contained in a particular workbook
Referring to objects in a collection
Worksheets(“Main”)
Charts(“XY”)
Complete object references
Application.Workbooks(“Project6”).Worksheets(“Main”).Range(“B16”)
Can be simplified when unambiguous
Workbooks(“Project6”).Worksheets(“Main”).Range(“B16”)
Worksheets(“Main”).Range(“B16”)
Range(“B16”)
Workbook
Worksheet
Chart
10
Object-oriented Programming & Variable “Scope”…
X
X
Y Y
Z
11
The “SCOPE” of a variable
How far is the “reach” of the variable, or
from where can the variable be “seen”?
1) only within a single procedure (Sub or Function)
such a variable is generally called a “local” variable
variable is declared using a Dim statement
within the procedure
2) only within the current module a “module” variable
declared using a Dim statement before the first
Sub or Function in the module
3) everywhere, in all procedures, in all modules open
declared using a Public statement at the module level 12
Module 1 Module 2
Dim k As Integer Public R As Single
One
Dolt
Two
Howdy
Current
Workbook/
VBA
project
6/14/2010
4
13
Where can k be referenced?
a) Everywhere in Module 1
b) Everywhere in Module 2
c) Anywhere not in Function Dolt
d) Only in Sub howdy
e) Everywhere
14
Where can R be referenced?
a) Only Module 1
b) Only Module 2
c) Only Function Dolt
d) Only Sub howdy
e) Everywhere
15
Where can y be referenced?
a) Only Module 1
b) Function Two and Function Dolt
c) Only Function Two
d) Only Sub Howdy
e) Everywhere
16
Where can j be referenced?
a) Only Module 1
b) Only Module 2
c) Only Sub Howdy
d) Only Function Two
e) Everywhere
6/14/2010
5
17
Static & Constant
Static y as Single
Static is used, instead of Dim, when you want the variable
to retain its value after the procedure is finished…i.e., if
you want the variable to have the same value the next time
the procedure is run.
Symbolic constants can be used to store values with names,
where the values should never change. Use the Const keyword
for this:
Const Rgas As Single = 8314.3
18
How to invoke Excel spreadsheet functions from VBA:
Application.WorksheetFunction.function-name (arguments)
Example: creating a function RangeArray
uses Min and Max functions in
Excel, not available in VBA
20
6/14/2010
6
21
UserForms
1) Design it
2) Set up code that processes what the user types into the
boxes & clicks on the radio buttons
3) Hook that code to the “Compute Re” button
4) Set up code that quits & hook it to the “Quit” button
5) Set up a way to bring up the form 22
UserForms
Insert a UserForm in the Visual Basic Editor (VBE)
Toolbox
contains
stuff to
put on
form
New &
empty
form
23
Properties
The Properties window
(in the bottom left corner
of the VBE) lists
properties of the selected
object – here, the
userform.
Use it to set those
properties…
24
Setting up the name and caption:
A user form is a variable and needs a
name (like any variable).
The Name is how you will refer to
the form.
The Caption is a property of the
form – what the user sees in the top
of the form:
6/14/2010
7
25
Add title and field for density
Properties window
now refers to the
label object
Change caption:
You don‟t need to change the Name since we‟re not going
to be modifying the label in our program. The Caption is
what‟s displayed on the User Form. 26
Add textbox for value
It‟s essential to name the textbox since that value will be taken
from the user and used in the program.
27
Add a “frame” to contain the units choices:
• Frames used to group similar objects.
• Exclusive OR
• Must be large enough to include all of the
choices you want to provide.
• Feel free to remove the caption for
aesthetic reasons (just remove the text in here)
28
Add an option button in the frame for one units choice
“stretch” button so
caption shows:
change title
& caption:
Again, option buttons MUST be named as that name will be
used in your code.
6/14/2010
8
29
Change default button value to true:
add button for alternate
units with caption and
default false:
30
Add similar entries for pipe diameter,
velocity and viscosity:
Easiest way: just copy each row and change the
names and captions in the corresponding
Properties window.
31
Add a command button to compute the answer:
32
Change command button name, caption & font:
The name of the command
button is the name of the VBA
subroutine that performs the
calculation
6/14/2010
9
33
Add a Quit button with similar formatting…
The name of that button is also used in your program.
34
The UserForm is now complete, but two important
features are missing:
1) there is no way for the UserForm to appear for use
2) when the Compute and Quit buttons are clicked,
nothing will happen because there is no VBA code
behind them
Hooking things up
35
Double-click the Compute Re button.
This will cause the following Sub wrapper to
pop up in a code module:
In here, we must add code
to carry out the necessary
calculations and display the
Reynolds Number result
Hooking VBA code to the “Compute Re” button…
36
Filling in that code:
• convert units, as required
• compute the Reynolds Number
• display the result
6/14/2010
10
37
This variable is
the name you
created for your
textbox
This is a variable
you create and
use in your
calculation.
Do NOT use the textbox name on the LHS of
your calculation – it will not work!! 38
What is the variable that VBA uses to return
whatever the user types here?
a) Diam
b) PipeDiameter
c) Pipe Diameter
39
What variable does this Sub use in its
calculations for this?
a) Diam
b) PipeDiameter
c) Pipe Diameter 40
What is the variable that VBA uses to return
whatever the user types here?
a) mu
b) viscosity
c) fluid viscosity
6/14/2010
11
41
How to run and remove user forms
insert a new module and add this Sub to start the UserForm
double-click the Quit button and add the code to remove
(“unload”) the UserForm
run the StartReynoldsNumber macro…
…and enter
values
with units
selected
42
UserForms
UserForms can be loaded automatically when the workbook
is opened. (This is called an “event handler.”) And they can also
be unloaded automatically when the workbook is closed.
1. Go to VBE and double click on thisworkbook item in Project
Explorer. (If Project Explorer doesn‟t show up, use view)
2. Change left field at top from General to Workbook.
3. Type in ReynoldsNumber.Show
(this is not on any exam; it‟s just a useful FYI)
43
Things to Remember!!!
• Create your own variables to carry out calculations, NOT the variables in the user form
• Make sure the variables from the user form that you assign to your created variables are the same names as in your user form
• These variables are those used from your text boxes and your option buttons, NOT your labels
• You should not have the same name for your text box as for your label
44
This variable is the
name you created
for your option
button
FormatNumber – number of digits after
the decimal point. Does not round.
6/14/2010
12
45
If you get a Reynolds number of 2134.3721 and the
program says MsgBox(FormatNumber(Re,1)), what
will the message box say?
a) 2134
b) 2135
c) 2134.3
d) 2134.37
e) 2134.4
46
MsgBox Function
MsgBox(“prompt”,buttons,”title”,helpfile,context)
optional
47
MsgBox Function
MsgBox(“prompt”,buttons,”title”,helpfile,context)
optional
Button codes
vbOKOnly vbExclamation
vbOKCancel vbInformation
vbAbortRetryIgnore vbDefaultButton1
vbYesNoCancel vbDefaultButton2
vbYesNo vbDefaultButton3
vbRetryCancel vbDefaultButton4
vbCritical vbSystemModal
vbQuestion
48
MsgBox Function
Putting line breaks into the message displayed:
MsgBox result is button clicked by user
top related