Beruflich Dokumente
Kultur Dokumente
Flow and
Making Decisions
Sharad K Singh
Controlling execution
Controlling execution
Controlling execution
Controlling execution
End Sub
Decisions, decisions
Sub GreetMe()
If Time < 0.5 Then MsgBox Good Morning
If Time >= 0.5 Then MsgBox Good Afternoon
End Sub
An If-Then-Else example
Another approach to the preceding
problem uses the Else clause. Heres the
same routine recoded to use the If-ThenElse structure:
Sub GreetMe()
If Time < 0.5 Then MsgBox Good Morning
Else MsgBox Good Afternoon
End Sub
An If-Then-Else example
VBA provides a slightly different way of coding If-ThenElse constructs that use an End-If statement.
Therefore, the GreetMe procedure can be rewritten as:
Sub GreetMe()
End Sub
An If-Then-Else example
An If-Then-Else example
An If-Then-Else example
Sub GreetMe2()
Dim Msg As String
If Time < 0.5 Then Msg = Morning
If Time >= 0.5 And Time < 0.75 Then Msg =
Afternoon
If Time >= 0.75 Then Msg = Evening
MsgBox Good & Msg
End Sub
An If-Then-Else example
Sub GreetMe4()
Dim Msg As String
If Time < 0.5 Then
Msg = Morning
Else
If Time >= 0.5 And Time < 0.75 Then
Msg = Afternoon
Else
Msg = Evening
End If
End If
MsgBox Good & Msg
End Sub
An If-Then-Else example
Using ElseIf
Sub GreetMe5()
Dim Msg As String
If Time < 0.5 Then
Msg = Morning
ElseIf Time >= 0.5 And Time < 0.75 Then
Msg = Afternoon
Else
Msg = Evening
End If
MsgBox Good & Msg
End Sub
End Sub
End Sub
End Select
End Select
MsgBox Discount: & Discount
End Sub
End Sub
you can put the statement on the same line as the Case keyword, preceded by a colon the VBA
statement separator character.
Loop
Loop
Bad Loop
Sub BadLoop()
Dim StartVal As Long
Dim NumToFill As Long
Dim CellCount As Long
StartVal = InputBox(Enter the starting value: )
NumToFill = InputBox(How many cells? )
ActiveCell = StartVal
CellCount = 1
DoAnother:
ActiveCell.Offset(CellCount, 0) = StartVal + CellCount
CellCount = CellCount + 1
If CellCount < NumToFill Then GoTo DoAnother _
Else Exit Sub
End Sub
For-Next loops
The simplest type of loop is a For-Next
loop. Heres the syntax for this structure:
For counter = start To end [Step stepval]
[statements]
[Exit For]
[statements]
Next [counter]
For-Next loops
Sub FillRange()
Dim Count As Long
For Count = 1 To 100
ActiveCell.Offset(Count - 1, 0) = Rnd
Next Count
End Sub
End Sub
Do-While loop
Do-While loop
Sub DoWhileDemo()
Do While ActiveCell.Value <> Empty
ActiveCell.Value = ActiveCell.Value * 2
ActiveCell.Offset(1, 0).Select
Loop
End Sub
Do-While loop
Do-Until loop
Do-Until loop
Sub DoUntilDemo()
Do Until IsEmpty(ActiveCell.Value)
ActiveCell.Value = ActiveCell.Value * 2
ActiveCell.Offset(1, 0).Select
Loop
End Sub
End Sub
End Sub
Next Cell
End Sub