week 9 dialogues and forms numerical integrationen1811/13s1/lects/week09-forms.pdf · engg1811 ©...
TRANSCRIPT
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 1
ENGG1811 Computing for Engineers
Week 9
Dialogues and Forms
Numerical Integration
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 2
References & Info
Chapra (Part 2 of ENGG1811 Text)
• Topic 21 (chapter 15) Custom Dialogue Boxes
This week’s schedule
Tue, Wed am: new material
Wed pm: worked example
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 3
Forms and Controls
VBA has access to the full window library
1. Buttons or similar Controls (window elements) can be placed on sheet.
2. Dialogues are provided for standard interaction such as opening files, choosing colours. Can be called from VBA.
3. Forms (windows with controls placed by the designer) can be embedded in document.
Each active element can trigger actions through VBA event procedures
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 4
1. Command Buttons
Simplest scheme: command buttons
• Show control tool box
Developer tab – Insert
2003: View – Toolbars – Control Toolbox
• Select command button from bottom group (ActiveX Controls, arrowed)
• Click and drag on sheet
• Right-click*, select Properties
• Change name (cmdDemo), caption, font, other
properties
• Right-click again, select View Code
• VBE allows changes to properties and event handler: cmdDemo_Click( )
• Exit design mode, button becomes active * or pick from Controls on the ribbon
Exit Design Mode
CommandButton
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 5
Example: Colour Swatch
• Lay out a new sheet with named ranges
ColourRegion (4 cells) and IndexBox (1 cell)
• Show the control box, add a button called cmdChangeColour labelled Next Colour
ColourRegion
IndexBox
Name box
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 6
Colour Swatch Event Procedure
• In Design Mode, double click button. Opens up VBA associated with this worksheet, including events for the command button.
• Sheet needs one variable, changed by the event procedure:
Const NUM_COLOURS = 56 ' Excel VBA standard (2003+ compatible)
Dim colLast As Integer ' last colour index shown (or 0)
Private Sub cmdChangeColour_Click()
colLast = 1 + colLast Mod NUM_COLOURS
With ActiveSheet
.Range("ColourRegion").Interior.ColorIndex = colLast
.Range("IndexBox").Value = colLast
End With
End Sub
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 7
Colour Swatch Demo
See sheet ColourSwatch on the week 9 Lecture demo spreadsheet.
This example is simple enough for all VBA code to be included with the sheet itself
Often cmdbuttonXYZ_Click() just calls a
subprogram in a module.
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 8
Properties Window
• Edit characteristics of any static object
• View by name or grouped by category
• Accessible from VBE or from control via Properties on shortcut menu or ribbon
• Units are points (1/72 inch, approx 28 pts per cm), 1 decimal place
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 9
2. Built-in Dialogues
• You’ve seen MsgBox before, now use its value:
reply = MsgBox("Root found, look for more?", _
vbYesNo, "Newton")
If reply = vbYes Then …
MsgBox "Out of jelly beans!", vbCritical ' OK only
Select Case MsgBox("I'm feeling tired, can I quit?", _
vbAbortRetryIgnore, "Ennui")
Case vbAbort: Application.Exit
Case vbIgnore: ' do nothing (keep going)
Case vbRetry: ' keep going anyway
End Select
Type msgbox to VBA Help for codes
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 10
Input box
• To issue a prompt and obtain a single string from the user you can use the InputBox function
Dim strName As String
strName = InputBox("What is Your name?")
If strName = "" Then
MsgBox "Silent type, eh?"
Else
MsgBox "Hello, " & strName
End If
• Occasionally useful, but large data sets should be on the active sheet, and smaller sets could have customised forms (soon)
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 11
Other Builtin Dialogues
• Getting the user to select a file name is a common requirement:
GetOpenFileName("Text Files (*.txt), *.txt")
• We would use this if we covered reading and writing to text files in ENGG1811 (but we don’t)
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 12
3. User Forms
A user form is an independent window containing controls placed by the designer
In the VBE, select
Insert - UserForm
Resize. From the toolbox, select and place controls.
Each is given a default name.
For our first example, add three labels, a text box and a command button
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 13
Toolbox Controls
Control Pfx Tool Graphic Main Properties*
Text box txt Value
Label lbl Caption
Command
button cmd Caption
List box lst Value, ControlSource
Combo box cbo Value , ControlSource
Option button opt Value (Boolean)
Check box chk Value
Spin button spn Value, Min, Max
Image img Picture
*All have Name, Width, Height, Left, Top, Visible, TabIndex etc
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 14
Control Properties
Can change most
attributes of each control (select with circled drop-down) in the Properties window. Important ones arrowed. See also
Categorized view.
Content
Identity
Text attributes
Position
Behaviour
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 15
Initiating Action
After designing the form, what then?
• All controls detect and manage events such as
frmGame_Activate() rdoGender_Change()
cmdGuess_Click() cmbAction_Change()
txtInput_AfterUpdate()
Private Sub lbl1_MouseMove(ByVal Button As Integer, _ ByVal Shift As Integer, ByVal X As Single)
• Each control’s properties are exposed through the object model, so VBA can use and modify them (especially displayed values)
• Must consider what should happen for each relevant event: event-driven programming
• Within event handlers normal algorithms apply
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 16
An Example
Let’s continue with the form we’re building, it’s for an implementation of the children’s High-Low guessing game
– program picks a number between 1 and n (say 100)
– user guesses, is told high/low/correct
– user wins if guessed within limited number of tries
• Can you identify the optimal strategy for the user (it’s certainly not random guessing!) ?
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 17
High-Low Form
Rename and reposition elements, add captions in 10pt font, adjust widths:
Added sample text in 14pt to confirm suitability of size.
lblResult is blank, content will be
assigned by VBA
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 18
Events
What (meaningful) events can occur?
1. Form is activated
2. Form is closed (via the window bar)
3. Reset button is pressed
4. User enters text
1 and 3 are the same; 2 isn’t handled
Hence only two need to be managed.
Event procedures:
cmdReset_Click()
txtGuess_AfterUpdate() why not txtGuess_Change()?
UserForm_Activate() – calls cmdReset_Click
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 19
Document Structure
Designs and VBA code are stored in three places in the document:
Module1 (rename it HiLo_module) has state variables and all algorithm processing code
Worksheet has VBA code to initiate form
frmHiLo has form layout, plus VBA code to handle all events
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 20
Startup
We want the form to appear when the sheet is selected (activated)
Use the worksheet activation event to position the form and activate it (Show method):
' Display the HiLo form, offset into Excel's window
Private Sub Worksheet_Activate()
frmHiLo.Left = Application.Top + 100
frmHiLo.Top = Application.Left + 100
frmHiLo.Show
End Sub
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 21
Event Responses
Pseudocode for Reset:
think of a number
set guess count to 0
clear lblResult.Caption and txtGuess.Value
Pseudocode for User entry:
fetch typed string (from txtGuess.Value)
if not a sensible guess then
issue error message (assign to lblResult.Caption)
elseif correctly guessed then
issue win message
elseif guess limit reached then
issue loss message
else
increment guess count
issue keep-trying message
dubious logic, allowing the software to be fooled much as viruses exploit logical errors in production software, such as passing a 100,000-character URL to a program that assumes nobody would ever do that!
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 22
State Variables
State is maintained in the visible elements and in two variables:
– target number
– number of guesses
These variables and additional procedures are stored in a new module (HiLo_module)
Event procedures should contain minimal code: they call procedures in HiLo_module to update
state
Must use fully qualified names: HiLo_module.PickRandomTarget
HiLo_module.ResetGuessCount
HiLo_module.Guess(strGuess)
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 23
Observation
Most of program consists of validating what the user typed
Exercise: add a checkbox labelled Show limits
If checked (chkShowLimits.Checked), display the current range of possible values based on what the player has guessed
– makes the game easier, especially if there were to be a time limit on each guess
– adds two controls (labels for the limits) and more VBA in return for richer functionality
– even fancier: two rectangular frames, one filled to show progress
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 24
Debugging
• Aim is to produce VBA procedures that perform exactly as intended
• Errors can be introduced at any stage
– design (poor understanding of problem)
– pseudocode (poor understanding of solution)
– implementation (poor understanding of VBA, or typos)
• VB Editor picks up gross typo-type errors only
• On execution, could get
– run-time error such as divide by zero
– run-time error such as invalid object method
– normal termination and correct result
– normal termination and incorrect result
• Different tests may produce different outcomes
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 25
Debugging
• VB interpreter has full control over the execution of your program
• If we get a run-time error, VBE shows current execution position
– Can view simple variable values to help infer error
• If result is wrong, it may be possible to work out the error, but often you need to know things like:
– What was the value of this variable at this point in the execution?
– How many times did this loop execute?
– When was this variable changed?
– Did this part of the procedure get executed?
• VBE can help you get answers to these questions
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 26
Error Handling
Programs can have errors of several kinds
1. Syntax and semantic errors due to typos or poor understanding of the language
2. Logical errors that produce a different outcome from the expected one
3. Run-time errors
The VB Editor can catch most of (1), and the programmer will use various techniques including debugging to deal with (2)
(3) normally stops the interpreter
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 27
Types of Run-time Error
a) Impossible calculations such as divide by zero
b) Exceeding data limits (integer overflow etc)
c) Array usage errors (index out of bounds)
d) Improper object usage (misspelled method or property, semantic error)
e) Missing or malformed data (no collection membership test, so this can happen easily)
(a) and (c) indicate logical errors or insufficient data validation
(b) may be a logical error, or wrong type used
(d) is a semantic error
(e) is a condition that can be detected and managed
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 28
Trapping Errors (Advanced topic)
On Error statement controls error handling
On Error GoTo label
On Error GoTo 0
On Error Resume Next
Error handlers are labelled statements local to a subprogram, often at the end, and preceded by Exit Sub statements
If an error occurs, transfer control to the labelled statement
Restore default handler (terminate execution on error)
Ignore error and continue with statement following the error
ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 31
Worked Example: Numeric Integration
Numerical integration approximates the solution to a
definite integral that may not have a closed form by using
a series of shapes to model the area under the curve
Simplest of these is the Trapezoidal Rule, which uses thin
vertical slices with a straight line at the top (forming
adjacent trapeziums)
a
f (x)
b
Integral of f (x)
from a to b
is approximated by
the sum of the areas
inside the
red trapeziums
ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 32
Trapezoidal Rule, theory
References: Wikipedia, many other web refs
Animation: http://math.fullerton.edu/mathews/a2001/Animations/Quadrature/Trape
zoidal/Trapezoidalaa.html
After doing the maths for n equally spaced panels, the
formula reduces to
*/)( ianabiaxwhere i
)()(2)(2)(2)(2
)( 1210 nn
b
a
xfxfxfxfxfdxxf
Twice the middle values
Panel width
n
ab
End-points counted
once only
ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 33
Trapezoidal Rule, pseudocode
We can easily convert this to pseudocode:
set sum to f (a) + f (b)
set delta to the panel width __________
For p = _____ To _____
add __________________ to sum
Next p
area = ______________
ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 34
Trapezoidal Rule, implementation
Function TrapArea(a As Double, b As Double, _
n As Integer) As Double
• Limitations: for this quick example, we will represent the
function to be integrated as a VBA function called directly
from TrapArea. It is possible to specify it as a formula on
the sheet, which is easier for end users
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 35
Summary
• Controls can be placed directly on the sheet to add interactivity between sheet and VBA
• Built-in dialogues are powerful but not universally available
• Forms provide more control over user interface
• Form programming focuses on events
• Debugging techniques include
– state display using Debug.Print
– state inspection after error or breakpoint
– single stepping, watch expressions
– careful code reviews
• Error handling regains control after unexpected program state transitions