VBA Logic & Loops PDF
VBA Logic & Loops PDF
January 4, 2012
Excel Files
programminglogic.xlsm
Outline
If, Then Logic
If, Then, Else
If, Then, ElseIf, Else
Select, Case
Looping
For Loops
For Each Loops
Do While Loops
Motivation
Dim x As Double
x = InputBox("Enter Number")
If x > 0 Then
MsgBox "Natural Logarithm = " & Log( x)
End If
Operator
=
<>
>
<
>=
<=
Description
Equal To
Not equal to
Strictly greater than
Strictly less than
Greater than or equal to
Less than or equal to
Operator
And
Or
Not
Description
All conditions must be true
At least one condition must be true
negate a condition
If x > 0 Then y = 5
instead of
If x > 0 Then
y = 5
End If
Dim x As Double
x = InputBox("Enter Number")
If x > 0 Then
MsgBox "Natural Logarithm = " & Log( x)
Else
MsgBox " The log function requires a positive number"
End If
Select, Case
It is often desirable to avoid a lot of complicated If, Then, ElseIf
statements. This is done with Select, Case.
Select Case testVal
Case Value1
statements if testVal = Value1
Case Value2
statements if testVal = Value2
.
.
.
Case ValueN
statements if testVal = ValueN
Case Else
statements if all tests fail
End Select
& discount_rate
& discount_rate
& discount_rate
& discount_rate
& discount_rate
& discount_rate
& discount_rate
& discount_rate
16
Looping
It is often desirable to loop or iterate over a range, an array, or
variable values. We will study:
I
For Loops
Do Loops
Looping
Use VBA Editor Help Function Illustration
18
For Loops
The components of the For loop
I
For Loops
See programminglogic.xls
Sub ForEx1()
Illustrate the For loop
Dim i As Integer
Dim total As Double
total = 0
For i = 1 To 20
total = total + i ^ 2
Next i
MsgBox "Total = " & total
total = 0
For i = 1 To 20 Step 2
total = total + i ^ 2
Debug.Print i
Next i
End Sub
For Loops
Important Concepts:
I
For Loops
I
I
For Loops
Loop over values in a range of unknown size
Illustrate looping over range of unknown size
Dim ws As Worksheet, isThere As Boolean
isThere = False
Dim i As Integer, N As Integer
Dim rng As Range, lastName As Range
Set rng = Range("names")
Set lastName = Range(rng.Cells(2, 2), _
rng.End(xlDown).Cells(1, 2))
N = lastName.Rows.Count
For i = 1 To N
If lastName.Cells(i, 1).Value = "Uehling" _
Then isThere = True
Next i
24
26