Visual Basic for Applications
Companion slides to http://blip.tv/file/3011639
© The Stanford Decisions and Ethics Center
decision.stanford.edu
On our agenda for today…
• Visual Basic for Applications
Buttons and Macros
• Lets create a simple button
Debugging
• MsgBox
• Debug.print (Immediate Window – Ctrl+G)
Iteration Logic
• While Loops Dim MyArray(5) As Double For I = 1 To 5 MyArray(I) = Rnd Next I For Each n In MyArray Debug.Print n Next n
Array Indexing Starts from 1
Iteration Logic
• While-Wend Loops
Dim MyArray(5) As Double I = 0
While i<5 MyArray(I) = Rnd
I = I+1 Wend For Each n In MyArray Debug.Print n Next n
Iteration Logic
• Do While
Do While conditionblah blah
Loop
Doblah blah
Loop While condition
Iteration Logic
• Do Until
Do Until conditionblah blah
Loop
Doblah blah
Loop Until condition
Conditional Logic
• Simple Conditionals
If condition_holds Then Do_something
Conditional Logic
• Nested Conditionals
If condition_holds Then Do_something
ElseIf another_condition_holds Then Do_something_else
End If
Conditional Logic
• More Nesting
If condition_holds Then Do_something
ElseIf another_condition_holds Then Do_something_else
ElseIf another_condition_holds Then Do_something_else
Else do_some_default_thing
End If
Example
• Armstrong Numbers
• Sum of the cubes of the Armstrong number = number itself
E.g. 153
1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
Reading and Writing
• From and to cells
• From and to cells in different worksheets
Functions and Subroutines
Sub Blah()
End Sub
Function Blah()
Blah = …
End Function
Refactoring
Any fool can write code that a computer
understands. Only a good programmer
can write code that a human understands.
Martin Fowler, in his classic, Refactoring
Refactoring
is changing design without changing functionality
Important refactorings for VBA• Decompose into Small Sub/Functions• Rename to use Intention-Revealing Names
Main MotivationONCE and ONLY ONCE
Getting Inputs
Dim Quantity As Variant Dim Discount As Double Quantity = InputBox("Enter Quantity: ") If Quantity = "" Then Exit Sub If Quantity >= 0 Then Discount = 0.1 If Quantity >= 25 Then Discount = 0.15 If Quantity >= 50 Then Discount = 0.2 If Quantity >= 75 Then Discount = 0.25 MsgBox "Discount: " & Discount
Select Case Dim Quantity As Variant Dim Discount As Double Quantity = InputBox("Enter Quantity: ") Select Case Quantity Case "" Exit Sub Case 0 To 24 Discount = 0.1 Case 25 To 49 Discount = 0.15 Case 50 To 74 Discount = 0.25 End Select MsgBox "Discount: " & Discount
Reffering to cells
Range(“name”).Value = NewValueRange(“A5”).value = …
Cells(..,..).Offset(..,..).ValueActiveCell.Offset(..,..).ValueRange(“..”).Offset(..,..).Value
ActiveSheet.Cells.ClearContents
Getting VBA Help
• Make sure the Help for VBA module is installed when installing Excel 2003
• Use ObjectBrowser