Professional Documents
Culture Documents
Sub Capitalcity()
If Worksheets("Sheet1").Cells(2, 1).Value = "UK" Then
Worksheets("Sheet1").Cells(2, 2).Value = "London"
End If
End Sub
Sub Capitalcity1()
If Worksheets("Sheet1").Cells(2, 1).Value = "US" Then
Worksheets("Sheet1").Cells(2, 2).Value = "Washington D.C"
Else
Worksheets("Sheet1").Cells(2, 2).Value = "Not US city"
End If
End Sub
IF program will always have a closing ‘END IF’ statement else VBA will give an error.
Looping Constructs
For….NEXT
This loop is used for a fixed number of times. In the below code, rownum is a variable and it will run 50 times till value 50 is
reached increasing by 1 each time –
Sub Forexample1()
Dim rownum as integer
FOR rownum = 1 to 50
Worksheets("Sheet1").Cells(rownum,1).Value = rownum
Next rownum
End Sub
Looping Constructs contd..
DO WHILE….Loop
This is like FOR statement just that it will keep on looping till the condition is true –
Sub DoWhileexample1()
Dim I As Integer
I=1
Do While I <= 10
Worksheets("Sheet2").Cells(I, 1).Value = I
I=I+2
Loop
End Sub
Looping Constructs contd..
DO UNTIL….Loop
This is like DO WHILE statement just that it will keep on looping till the condition is not met –
Sub DoUntilexample1()
Dim I As Integer
I=1
Do Until I = 11
Worksheets("Sheet2").Cells(I, 2).Value = I
I=I+2
Loop
End Sub
In the above example, if you change the condition of Do Until I = 10 instead of 11, since I will never reach this value 10, as 1+2
= 3, then 3+2 = 5 and so on.. i.e. we will have only odd numbers, excel will keep on running till value of I is 32,767 which is the
maximum value a variable declared as integer can take.
Sub DoWhileexample2()
Dim I As Integer
I=1
Do
Worksheets("Sheet2").Cells(I, 1).Value = I
I=I+2
Loop While I <= 10
End Sub
Sub DoUntilexample2()
Dim I As Integer
I=1
Do
Worksheets("Sheet2").Cells(I, 2).Value = I
I=I+2
Loop Until I = 11
End Sub
Looping Constructs contd..
Select Case construct
Using this condition, you can choose from two or more options – let’s suppose we have country name in cell A2 which can be
either UK, US or India and depending on which country we have, we will place the value of its capital in cell B2. The program
will look like following –
Sub selectcaseexample1()
Select Case Worksheets("Sheet1").Cells(2, 1).Value
Case Is = "UK"
Worksheets("Sheet1").Cells(2, 2).Value = "London"
Case Is = "US"
Worksheets("Sheet1").Cells(2, 2).Value = "Washington D.C"
Case Is = "India"
Worksheets("Sheet1").Cells(2, 2).Value = "New Delhi"
End Select
End Sub