Learn if, else, and select statements in VB6

Level:
Level2

Written By TheVBProgramer.

The selection control structure allows one set of statements to be executed if a condition is true and another set of actions to be executed if a condition is false. A selection structure, also called an "If-Then-Else" structure, is flowcharted as follows:

After either the true set of actions or the false set of actions are taken, program control resumes with the next statement (the statement that would be placed below the connector in the flowchart above).

 

In VB, the following form is preferred for implementing the If-Then-Else structure (this is the "block", or "multi-line" form of the If statement):

 

If <conditional expression> Then

<one or more statements to be executed if condition is true>

Else

<one or more statements to be executed if condition is false>

End If

 

If the conditional expression is true, the statements between the keywords Then and Else will be executed (and the statements between the keywords Else and End If will be bypassed). If the conditional expression is false, the statements between the keywords Else and End If will be executed (and the statements between the keywords Then and Else will be bypassed). In any case, program control will resume with the statement following End If.

 

Example:

 

If sngNumberOfCredits < 12 Then

lblStatus = "PART-TIME STUDENT"

dblTuitionAmount = sngNumberOfCredits * 175

Else

lblStatus = "FULL-TIME STUDENT"

dblTuitionAmount = 2000

End If

 

STYLE TIPS FOR THE BLOCK IF STATEMENT:

(1) Indent the "true" actions 4 spaces from the keyword "If"

(2) Code the keyword "Else" on a separate line, aligned with the keyword "If"

(3) Code the "false" actions 4 spaces from the keyword "Else"

(4) Align the keywords "End If" with the keywords "If" and "Else"

 

The If-Then-Else statement is a "two-alternative" decision - actions are taken on both the "If" side and the "Else" side. Sometimes, however, you may only want to perform an action or set of actions if a condition is true, but do nothing special if the condition is false. This could be flowcharted as follows:

 

To implement this in VB, omit the "Else" portion of the block If structure. For example:

 

If dblTotalSales > 100000 Then

dblBonusAmount = 500

End If

 

 

 


To maintain compatibility with older versions of BASIC, the "single-line" If statement is available. The format is:

 

If <conditional expression> Then <true statement> [Else <false statement>]

 

Examples:

If sngTemperature <= 32 Then Print "It's freezing!"

 

If sngAvgGrade >= 60 Then Print "You passed!" Else Print "You failed!"

 

Note that in the single-line format of the If statement, the keywords End If are not used.

 

Style-wise, the block form of the If statement is preferred over the single-line form in that the block form enhances readability.

 

Although not used frequently, in the block form of the If statement, "null" or "empty" sets of actions are permitted (i.e., "if a condition is true, do nothing - else, do something"). For example:

 

If sngTemperature > 32 Then

Else

Print "It's freezing!"

End If

 

When using an empty set of actions, it improves readability to place a comment (remark) where the true statements would normally go:

 

If sngTemperature > 32 Then

'Do nothing

Else

Print "It's freezing!"

End If

 

Similarly, an empty set of actions could follow an Else:

 

If sngTemperature <= 32 Then

Print "It's freezing!"

Else

'Do nothing

End If

 

Using Boolean Variables as Conditional Expressions

 

A Boolean variable, which can hold the value True or False, can be used anywhere a relational expression can be used.

 

Example:

 

If blnFoundIt Then . . .

 

can be coded instead of:

 

If blnFoundIt = True Then . . .

 

in other words, the "= True" part is implied.

 

Also, to test if a Boolean variable is false, you can use:

 

If Not blnFoundIt Then . . .

 

instead of:

 

If blnFoundIt = False Then . . .

 

 

The IIf (Immediate If) Function

 

For cases where you want to assign a particular variable one value if a condition true and another value if a condition is false, you can use the IIf function. The syntax is:

 

IIf(<conditional expression>, true part, false part)

 

The statement

 

strMessage = IIf(sngAvgGrade >= 60, "You passed!", "You failed!")

 

is equivalent to

 

If sngAvgGrade >= 60 Then

strMessage = "You passed!"

Else

strMessage = "You failed!"

End If

 

The Case Structure

 

When the situation arises where you need to choose between more than two alternatives, an extended form of the selection structure, called the case structure, must be used. A flowcharted example follows:

In VB, the case structure can be implemented in one of two ways: with an extended block If structure, or with the Select Case statement structure.

 

Extended Block If Statement (If/Then/ElseIf)

 

Format:

If <conditional expression 1> Then

<one or more statements to be executed if condition 1 is true>

ElseIf <conditional expression 2> Then

<one or more statements to be executed if condition 2 is true>

. . .

ElseIf <conditional expression n> Then

<one or more statements to be executed if condition n is true>

Else

<one or more statements to be executed if none of the above conditions is true>

End If

 

Note that one or more ElseIf clauses are "sandwiched" between the first "If" clause and the last "Else" clause. Note also the keyword ElseIf is one word. Using the format above, this extended If structure is to be understood as follows: if "conditional expression 1" is true, perform the statements associated with that condition, then exit to the statement following the End If; if "conditional expression 1" is false, then check "conditional expression 2" - if "conditional expression 2" is true, perform the statements associated with that condition, then exit to the statement following the End If, and so on. VB will execute the statements associated with the first true conditional expression it finds and then exit to the statement following the End If. The final Else statement is often useful to trap errors that may occur when unexpected conditions arise, none of which matches the conditions in the previous If or ElseIf clauses.

 

Example:

 

If strShiftCode = "1" Then

sngShiftRate = sngHourlyRate

ElseIf strShiftCode = "2" Then

sngShiftRate = sngHourlyRate * 1.1

ElseIf strShiftCode = "3" Then

sngShiftRate = sngHourlyRate * 1.15

Else

Print "Shift code error"

End If

 

The example above also shows the recommended style for indenting.

 

Note that the use of "ElseIf" saves the coding of multiple "End If" statements in a nested If structure. As a comparison, the above example could have been written as follows:

 

If strShiftCode = "1" Then

sngShiftRate = sngHourlyRate

Else

If strShiftCode = "2" Then

sngShiftRate = sngHourlyRate * 1.1

Else

If strShiftCode = "3" Then

sngShiftRate = sngHourlyRate * 1.15

Else

Print "Shift code error"

End If

End If

End If

 

 

The Select Case Statement

 

VB's Select Case is a powerful statement with several options. The format is:

 

Select Case <test expression>

Case <expression list 1>

<statement list 1>

Case <expression list 2>

<statement list 2>

…

Case Else

<statement list n>

End Select

 

The format above is to be understood as follows: The Select Case statement specifies an expression to be tested. Each subsequent Case clause specifies an expression(s) that the test expression will be compared to. The first Case clause that contains an expression that matches the test expression will have its associated actions executed, then program control will branch to the statement following End Select. The final Case Else clause is often useful to trap errors that may occur when an unexpected value of the test expression is present, none of which matches the expression list specified in any of the above Case clauses.

 

Example:

Select Case strShiftCode

Case "1"

sngShiftRate = sngHourlyRate

Case "2"

sngShiftRate = sngHourlyRate * 1.1

Case "3"

sngShiftRate = sngHourlyRate * 1.5

Case Else

Print "Shift Code Error"

End Select

 

The example above also shows the recommended style for indenting.

 

The test expression following "Select Case" can be a more complex expression, such as:

 

Select Case intNumber + 1

Select Case Mid$(strTest, 4, 2)

 

The expression list in a "Case" clause can have any of the following formats:

 

Format

Examples

<expression> [, expression, . . . ]

Case 1, 10, 100

Case "Y", "y"

<expression> To <expression>

Case 1 To 9

Case "A" To "C"

Is <relational operator expression>

Case Is >= 21

(combination of any of the above)

Case Is <= 5, 20 To 29, 43

 

The Select Case statement does not need to be "tied" to one particular variable or expression; it can be used to evaluate any number of conditions, using the following format:

 

Select Case True

Case <condition 1>

<statement list 1>

Case < condition 2>

<statement list 2>

…

Case Else

<statement list n>

End Select

If you enjoyed this post, subscribe for updates (it's free)

thanks for your tutorials on

thanks for your tutorials on select case
could you please give an example in an array situation. thus, allow the user to enter marks and assign grades based on a given grading system.
thank you in advance

Reply to "Can you please widen the..."

I don't think its allowed to mix two different statements together ( if and case ) correct me if I'm wrong, also as said above you're using two different data types on is a number ( integer ) which was not declared any variable so the computer dose not understand what you meant by Case 1 e.t.c earlier. Try out the following code in VB6. I have dry run it and tested it out myself.

With case select statements you just select a variable ( something ) to be tested, the case's act like "in case such and such happens" then
under them you state what the computer should do e.t.c, its not confusing but the first time I learned case statements I thought they where so complex but their even more simple than if statements once you get used to the syntax.

private sub command1_click()

Dim Cnt As Integer
Text2.text = Cnt
Text1.text = "mama"
select case Cnt

case 0
Text1.text = "a"
case 1
Text1.text="b"

end select
end sub

Sorry I spotted a small bug

Sorry I spotted a small bug with the Cnt, Text2.Text in order to be "read" by the computer as an Integer needs to be written as Val(Text2.Text). Then I'm not sure if the text is initially supposed to be "mama" or is that for the else statement.

Private Sub command1_click()

Dim Cnt As Integer
Cnt = Val(Text2.Text)

Select Case Cnt

Case 0
Text1.Text = "a"
Case 1
Text1.Text = "b"
Case Else
Text1.Text = "mama"

End Select
End Sub

P.S Greetings from another earth!

d system will add a information with a fixed A.NO,Copies in SQL

HI! good day! I'm having a problem with my vb. Im trying to do this:
QTY : 3
A.No: 0001 (this textbox has a format and disable)
.. If i look in my SQL the data should be
A.NO TITLE
0001 abscv
0002 afa
0003 asf
the system will add a information with a fixed A.NO, If I put the quantity for example 5. the result in my SQL should be 5 copies... I dont know how to explain. but I used If code. This is the code
Dim i As Integer
i = Val(txtqty.text)
If i >= 1 Then
rs.AddNew
rs!AccessionNo = txtAccessionNo.text + i
' a = rs!AccessionNo
' txtAccessionNo.text = Format(a + 1, "00000")
' Else
' txtAccessionNo.text = "00001"
End If

rs.Update
--
but this is wrong.
the output of this code
is (let say I input 5 in the qty)
A.No Title
0001 sfasfa
5 null
what should i do??
Is the "IF" code is wrong? should I use loop???

please help

What you write after the

What you write after the case statement is what you want to compare 'mama' to
For example:

  1. Private Sub Command1_Click()
  2. ' Get the weekday
  3. Dim weekday As String
  4. weekday = InputBox ("What day of the week is it?")
  5.  
  6. ' Display a message
  7. Select Case weekday
  8. Case "Monday": MsgBox ("Don't you have Mondays?")
  9. Case "Tuesday", "Wednesday", "Thursday": MsgBox ("Another day another dollar")
  10. Case "Friday": MsgBox ("TGIF")
  11. Case "Saturday", "Sunday": MsgBox ("Sleep-in time!")
  12. Case Else: MsgBox ("That's not a weekday!")
  13. End Select
  14. End Sub

can you please widen the

can you please widen the select case topic more? because i understood it but not quite sure on how to use it. i tried it with this code but it nothing happens

private sub command1_click()
mama=text1.text
select case mama
case 0
if text2.text="a" then
text1.text="a'
end if
case 1
if text2.text="b" then
text1.text="b"
end if
end select
end sub

Select Case

When you compare the value in the Case part, it has to be coded as the same data type. In your example, you are using a text field (mama = text1.text), but your Case values are coded as integers, so the match never happens. Try Case "0" instead of Case 0 and Case "1" instead of Case 1. You should also code a Case Else for when the text value is neither of the two.