Visual Basic If…Then…Else 语句
If 语句可以跟随一个可选的 Else 语句,当布尔表达式为 false 时执行该语句。
语法
VB 中的 If…Then…Else 语句的语法如下:
If(boolean_expression)Then'当 boolean_expression 为 true,则执行这里的语句Else'当 boolean_expression 为 false,则执行这里的语句End If
如果布尔表达式的计算结果为 true,则将执行 if 代码块,否则将执行代码块。
流程图

实例
Module decisionsSub Main()'local variable definition 'Dim a As Integer = 100' check the boolean condition using if statement 'If (a < 20) Then' if condition is true then print the following 'Console.WriteLine("a is less than 20")Else' if condition is false then print the following 'Console.WriteLine("a is not less than 20")End IfConsole.WriteLine("value of a is : {0}", a)Console.ReadLine()End SubEnd Module
结果如下:
a is not less than 20value of a is : 100
If…Else If…Else 语句
If 语句后面可以跟一个可选的 Else if…Else 语句,这对使用单个 If…Else If 语句判断各种条件非常有用。
当使用 If…Else If…Else 语句时,有几点要注意。
- 一个
If可以有零个或一个Else,它必须在一个Else If之后。 - 一个如果可以有零到许多
Else If,但它们必须在Else之前。 - 当有一个
Else if成功,其余Else If或Else将不会再进行判断执行。
语法
VB 中的 if…else if…else 语句的语法如下:
If(boolean_expression 1)Then' 当 boolean_expression 1 为 true 时执行ElseIf( boolean_expression 2)Then' 当 boolean_expression 2 为 true 时执行ElseIf( boolean_expression 3)Then' 当 boolean_expression 3 为 true 时执行Else' 当上面的表达式都不为 true 时执行End If
实例
Module decisionsSub Main()'local variable definition 'Dim a As Integer = 100' check the boolean condition 'If (a = 10) Then' if condition is true then print the following 'Console.WriteLine("Value of a is 10") 'ElseIf (a = 20) Then'if else if condition is true 'Console.WriteLine("Value of a is 20") 'ElseIf (a = 30) Then'if else if condition is trueConsole.WriteLine("Value of a is 30")Else'if none of the conditions is trueConsole.WriteLine("None of the values is matching")End IfConsole.WriteLine("Exact value of a is: {0}", a)Console.ReadLine()End SubEnd Module
结果如下:
None of the values is matchingExact value of a is: 100