How to Write an If Statement in Visual Basic
- 1). Load your Visual Basic application. When the application loads, you have a Solution Explorer on the right side that creates a default form. Right-click the form and select "View Code." This creates a code-behind file in your console workspace.
- 2). Create two variables. An "If" statement is used to compare two variables. For this example, two numbers are compared. The code below creates two integer variables that will be used in the If statement:
Dim int1 as Integer
Dim int2 as Integer
int1 = 1
int1 = 2 - 3). Create the If statement. The If statement is created in a block of code. In the code below, the If statement checks if int1 is less than int2:
If int1 < int2 Then
Enter code here
End If
The block above sets up the If statement. The "Enter code here" is executed only if the If statement returns true. - 4). Fill in the If statement code. Now that your logic for the If statement is set up, you can add some code within the block that will execute. For this example, a message box is shown to the user. The full If statement block is shown below:
If int1 < int2 Then
MsgBox "The int1 variable is less than int2"
End If
In the example above, the message is only shown if int1 is smaller than int2 - 5). Save the file and press the F5 key. This runs the application in debug mode where you can test the If statement code.
Source...