Select Case

Visual Basic provides the Select Case structure as an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable.

A Select Case structure works with a single test expression that is evaluated once, at the top of the structure. Visual Basic then compares the result of this expression with the values for each Case in the structure. If there is a match, it executes the block of statements associated with that Case:


Select Case testexpression
[Case expressionlist1
[statementblock-1]]
[Case expressionlist2
[statementblock-2]]
.
.
.
[Case Else
[statementblock-n]]
End Select

Each expressionlist is a list of one or more values. If there is more than one value in a single list, the values are separated by commas. Each statementblock contains zero or more statements. If more than one Case matches the test expression, only the statement block associated with the first matching Case will execute. Visual Basic executes statements in the Case Else clause (which is optional) if none of the values in the expression lists matches the test expression. For example, suppose you added another command to the Edit menu in the If...Then...ElseIf example. You could add another ElseIf clause, or you could write the function with Select Case:

Ø Select Case using Ordinal values

Private Sub mnuCut_Click (Index As Integer)

Select Case Index

Case 0 ' Cut command.

CopyActiveControl ' Call general procedures.

ClearActiveControl

Case 1 ' Copy command.

CopyActiveControl

Case 2 ' Clear command.

ClearActiveControl

Case 3 ' Paste command.

PasteActiveControl

Case Else

frmFind.Show ' Show Find dialog box.

End Select

End Sub


No comments:

Post a Comment