VBScript 条件语句

实例

If...then..else 语句
本例演示如何编写 if...then..else 语句。
If...then..elseif 语句
本例演示如何编写 if...then...elseif... 语句。
Select case 语句
本例演示如何编写 select case 语句。

条件语句

经常地,当我们编写代码时,我们需要根据不同的判断执行不同操作。我们可以使用条件语句完成这个工作。

在 VBScript 我们可以使用三种条件语句:

if 语句
假如你希望在条件为 true 时执行一系列的代码,可以使用这个语句。
if...then...else 语句
假如你希望执行两套代码其中之一,可以使用这个语句。
if...then...elseif 语句
假如你希望选择多套代码之一来执行,可以使用这个语句。
select case 语句
假如你希望选择多套代码之一来执行,可以使用这个语句。

If....Then.....Else

在下面的情况中,您可以使用 If...Then...Else 语句:

  • 在条件为 true 时,执行某段代码
  • 选择两段代码之一来执行时

如果需要在条件为 true 时只执行一行语句,可以把代码写为一行:

if i=10 Then msgbox "Hello"

在上面的代码中,没有 .else.. 语句。我们仅仅让代码在条件为 true 时执行一项操作(当 i 为 10 时)。

假如我们需要在条件为 true 时执行不止一条语句,那么就必须在一行写一条语句,然后使用关键词 "End If" 来结束这个语句:

if i=10 Then
   msgbox "Hello"
   i = i+1
end If

在上面的代码中,同样没有 .else.. 语句。我们仅仅让代码在条件为 true 时执行了多项操作。

假如我们希望在条件为 true 时执行某条语句,并当条件不为 true 时执行另一条语句,就必须添加关键词 "Else":

if i=10 then
   msgbox "Hello"
else
   msgbox "Goodbye"
end If

当条件为 true 时会执行第一段代码,当条件不成立时执行第二段代码(当 i 不等于 10 时)。

If....Then.....Elseif

假如你希望选择多套代码之一来执行,可以使用if...then...elseif语句:

if payment="Cash" then
   msgbox "You are going to pay cash!"
 elseif payment="Visa" then
   msgbox "You are going to pay with visa."
 elseif payment="AmEx" then
   msgbox "You are going to pay with American Express."
 else
   msgbox "Unknown method of payment."
end If

Select Case

假如你希望选择多套代码之一来执行,可以使用 SELECT 语句:

select case payment
 case "Cash"
   msgbox "You are going to pay cash"
 case "Visa"
   msgbox "You are going to pay with visa"
 case "AmEx"
   msgbox "You are going to pay with American Express"
 case Else
   msgbox "Unknown method of payment"
end select

以上代码的工作原理:首先,我们需要一个简单的表达式(常常是一个变量),并且这个表达式会被做一次求值运算。然后,表达式的值会与每个 case 中的值作比较,如果匹配,被匹配的 case 所对应的代码会被执行。