根据条件的值,可使用 If...Then...Else 语句运行指定的语句或一个语句块。If...Then...Else 语句可根据需要嵌套多级。然而,为了可读性可能会使用 Select Case 语句而不使用多嵌套级的 If...Then...Else 语句。
当条件为 True 时,若只要执行一个语句,则可以使用单行的 If...Then...Else 语法。下列的示例显示了单行语法,省略了 Else 关键字:
Sub FixDate() myDate = #2/13/95# If myDate < Now Then myDate = NowEnd Sub
为了运行多行代码,必须使用多行的语法。而此语法包含 End If 语句,如同下面示例所示:
Sub AlertUser(value as Long) If value = 0 Then AlertLabel.ForeColor = "Red" AlertLabel.Font.Bold = True AlertLabel.Font.Italic = True End IfEnd Sub
使用 If...Then...Else 语句可以定义两个可执行的语句块:其中一个块会在条件为True 时执行;而另一个块会在条件为 False 时执行。
Sub AlertUser(value as Long) If value = 0 Then AlertLabel.ForeColor = vbRed AlertLabel.Font.Bold = True AlertLabel.Font.Italic = True Else AlertLabel.Forecolor = vbBlack AlertLabel.Font.Bold = False AlertLabel.Font.Italic = False End IfEnd Sub
如果第一个条件为 False,则可以在 If...Then...Else 语句中加上 ElseIf 语句来测试第二个条件。例如,下列的函数过程根据工作分类来计算奖金。如果所有 If 和 ElseIf 语句中条件都是 False,则会运行跟在 Else 语句之后的语句。
Function Bonus(performance, salary) If performance = 1 Then Bonus = salary * 0.1 ElseIf performance = 2 Then Bonus = salary * 0.09 ElseIf performance = 3 Then Bonus = salary * 0.07 Else Bonus = 0 End IfEnd Function
联系客服