Thursday, December 17, 2009

Select Case VBA

Select Case is similar to if....Then .....Else ,except that you can choose from several condition values.

The general form is

Select Case expression
Case Value1
one or more VB statements for action1
Case Value2
one or more VB statements for action2
.....
.....
Case Valuem
one or more VB statements for actionm
[case else
one or more statements for action otherwise]
End Select

You can have as many case lines as you like and you can have more than one value on each line. You can even have a range of values by using To.


Example:

In the following example, the variable n takes as its value the content of the active cell. Control the passes to the corresponding Case statement.

Note the use of To in one of the case statements.

n = Activecell
select case n
case 12
statementA
case 24, 36
statementB
case 48 To 96
statementC
....
....
Case Else
statementD
end select

Else statement is a replacement of  if statement when we need to be right more if statement.....

IF statement in VBA

If statement is basically a single condition base statement. If statement is basically known as
If....then statement

Syntax:
If condition Then statement1 [Else statement2]

If the condition is satisfied (true then statement1 is carried out otherwise control passes to statement2.

Usually you will need to use the block statement. If.....then ....else which does not restrict you to one line of code. This has the form.

Example:
This macro looks at the value in A1. If it is 100 it enters the text Full marks in B1. If the value in A1 is not 100, the macro enters No in B1.

Sub fullmarks()
sheets("sheet1").select
cells(1,1).select
If activecell = 100 Then
cells(1,2).value = "No"
End if
end sub

Note: You could omit the line Cells(1,1).Select and change the following line to if cells(1,1) = 100 then.

Subscribe Now: From your browser

Search:

Learn Office Excel