📜  VBA嵌套的If语句

📅  最后修改于: 2021-01-11 14:12:24             🧑  作者: Mango

嵌套的if语句

另一个If或ElseIf语句内的If或ElseIf语句。内部If语句的执行基于最外面的If语句。这使VBScript可以处理复杂的条件。

句法

If (Boolean_expression) Then
Statement 1
........
........
........
Statement n
If (Boolean_expression) Then
Statement 1
.........
.........
Statement n
ElseIf (Boolean_expression) Then
Statement 1
.........
.........
Statement n
Else
Statement 1
.........
.........
Statement n
End If
Else
Statement 1
.........
.........
Statement n
End If

流程图

在嵌套语句中,即使在评估True条件(并执行其关联的语句)之后,VBA也会遍历每个If … Then条件,而在ElseIf结构中,在评估True条件后将跳过以下所有条件。

在这种情况下,ElseIf结构会更快。因此,如果可以使用ElseIf结构完成嵌套语句,则嵌套语句可能不包含非常有效的方法。

例如:假设您想编写一个代码,如果学生分数大于或等于80,则返回优秀消息。根据以下示例所示的判定标准,返回良好,平均和较差,例如:

Sub Macro1()
Dim sngMarks As Single
sngMarks = 70
If sngMarks >= 80 Then
MsgBox "Excellent"
End If
If sngMarks >= 60 And sngMarks < 80 Then
MsgBox "Good"
End If
If sngMarks >= 40 And sngMarks < 60 Then
MsgBox "Average"
End If
If sngMarks < 40 Then
MsgBox "Poor"
End If
End Sub

在VBA中运行上面的代码,您将获得输出,如下面的屏幕快照所示。

让我们借助一个函数找到Excel的正数。

Private Sub nested_If_demo_Click ()
Dim x As Integer 
x = 30 
If x > 0 Then 
MsgBox "a number is a positive number"
If x = 1 Then
MsgBox "A number is neither prime nor composite"
ElseIf x = 2 Then 
MsgBox "A number is the only prime even prime number"
ElseIf x = 3 Then 
MsgBox "A number is the least odd prime number"
Else 
MsgBox "The number is not 0, 1, 2, or 3"
End If 
Else If x < 0 Then
MsgBox "A number is a negative number"
Else 
MsgBox "the number is zero"
End If
End Sub

执行完上面的代码后,您将获得如下输出:

A number is a positive number 
The number is not 0, 1, 2, or 3