How to Code an If Else Statement in VB6

How to Code an If Else Statement in VB6

Visual Basic 6 (VB6) is an event-driven programming language. In response to an event such as a button click, VB6 normally runs a series of commands, one after another. However, you may want the computer to run different sets of commands depending on whether a condition is true or not. To do this, it is best to use an "If...Else" statement.

Instructions

    1

    Type "If [condition] Then" where "[condition]" is the condition you want to test. For example, this code would test whether some text entered by the user is less than three characters long:

    If Len(txtUsername.Text) < 3 Then

    2

    Enter the commands you want run if the condition is true. You can enter a single command or several, each on its own line. These commands are sometimes referred to as a "block." For example, this command is used to inform the user that the text he entered is too short:

    MsgBox "Usernames must be at least three characters long."

    3

    Enter the keyword "Else" on its own line. This marks the end of the block of commands to be run if the condition is true, and the beginning of the block of commands to be run if the condition is not true. For example:

    Else

    4

    Enter the commands you want run if the condition is not true. As with the previous block, you can enter one or many commands. This example saves the text the user entered and tells him that it was saved:

    Username = txtUsername.Text

    MsgBox "Your new username is " & Username & "."

    5

    Type "End If" on its own line to mark the end of the "If...Else" statement. For reference, here is the code for the entire example:

    If Len(txtUsername.Text) < 3 Then

    MsgBox "Usernames must be at least three characters long."

    Else

    Username = txtUsername.Text

    MsgBox "Your new username is " & Username & "."

    End If

Blog Archive