You are on page 1of 8

If Statement

If condition Then If condition Then If condition Then


. . . . . . . . .

End If Else ElseIF condition Then


. . . . . .
End If ElseIF condition Then
. . .
Else
condition . . .
Must evaluate to True or False
End If
Then
Required, and it should be in the same line with If or ElseIF

ELseIF
is a single word should not be separated
Sub Example1()
If Cells(1, 1) = 0 Then
Cells(2, 1) = "A1 is Zero"
End If
End Sub

Sub Example2()
A = 5
B = 10
If A >= B Then
Cells(1, 1) = "A is greater or equal than B"
Else
Cells(1, 1) = "B is greater than A"
End If
End Sub
Sub Example3()

For i = 1 To 10

Reminder = Cells(i, 1) Mod 2

If Reminder = 0 Then

Cells(i, 2) = "Even"

Else

Cells(i, 2) = "Odd"

End If

Next i

End Sub
Sub Example4()

For i = 1 To 10

a = Cells(i, 1)

If a > 0 Then

Cells(i, 2) = "Positive"

ElseIf a < 0 Then

Cells(i, 2) = "Negative"

Else

Cells(i, 2) = "Zero"

End If

Next i

End Sub
Exercise 1: using a for loop find the count of the odd numbers in the cells
A1 to A10, place the result in cell C1

Sub Exercise1()
Count = 0
For i = 1 To 10
a = Cells(i, 1) Mod 2
If a <> 0 Then
Count = Count + 1
End If
Next i
Cells(1, 3) = Count
End Sub
Exercise 2: Find the average of the absolute values in the in the range
A1 to C5, place the result in cell B7.

Sub Exercise2() Sub Exercise2()


Sum = 0 Sum = 0
For r = 1 To 5 For r = 1 To 5
For c = 1 To 3 For c = 1 To 3
A = Cells(r, c) A = Cells(r, c)
If A > 0 Then If A < 0 Then
Sum = Sum + A A = A * -1
Else End If
Sum = Sum - A Sum = Sum + A
End If Next c
Next c Next r
Next r Cells(7, 2) = Sum / 15
Cells(7, 2) = Sum / 15 End Sub
End Sub
Sub Exercise3()
Exercise 3: Compare the number in
Equal = 0
the cell A4 with the content of the
Grater = 0
cells A1 to F1 and find the count of
Smaller = 0
the numbers that are:
A = Cells(4, 1)
1. Equal to A4 content. For i = 1 To 9
2. Grater than A4 content. If cells(1,i) = a Then
3. Smaller than A4 content. Equal = Equal + 1
Elseif cells(1,i) > a Then
Display the result as shown in the
Grater = Grater + 1
picture below Else
Smaller = Smaller + 1
End If
Next i
Cells(6, 2) = Equal
Cells(7, 2) = Grater
Cells(8, 2) = Smaller
End Sub
Exercise 4: Find the average for each student and put the result in row 7
as shown in the figure.
Sub Exercise1()
For i = 2 To 5
S=0
For j = 2 To 6
S = S + Cells(j, i)
Next j
Cells(7, i) = S / 5
Next i
End Sub

You might also like