VBA中的选择结构If ...Then ...ElseIf...Else;Select Case...Case Else...

发布时间 2023-06-15 09:09:31作者: iZJ"Qq4577105

If ElseIf Else结构的基本语法如下:

If 条件表达式1 Then
    '表达式1真时,执行的代码
ElseIf 条件表达式2 Then
    '表达式2真时,执行的代码
ElseIf 条件表达式3 Then
    '表达式3真时,执行的代码
    ...
ElseIf 条件表达式n Then
    '表达式n真时,执行的代码
Else
    '以上表达式都不为真时,执行的代码
End If

示例:

Sub MyCode()

    Dim i As Integer
    
    For i = 2 To 10
    
        If Cells(i, "B").Value >= 85 Then
            Cells(i, "D") = "优"
        ElseIf Cells(i, "B").Value >= 75 Then
            Cells(i, "D") = "良"
        ElseIf Cells(i, "B").Value >= 60 Then
            Cells(i, "D") = "及格"
        Else
            Cells(i, "D") = "不及格"
        End If
        
    Next i

End Sub

结果:

 

Select Case

Select Case 变量
	Case 判断条件 1
    	'条件 1 真时,执行的代码
	Case 判断条件 2
    	'条件 2 真时,执行的代码
	Case 判断条件 3
    	'条件 3 真时,执行的代码
    Case Else
    	'之前的所有条件都不为真时,执行的代码
End Select

示例:

Sub MyCode()

    Dim i As Integer
    
    For i = 2 To 10
    
        Select Case Cells(i, "B").Value
            Case Is >= 85
                Cells(i, "D") = "优"
            Case Is >= 75
                Cells(i, "D") = "良"
            Case Is >= 60
                Cells(i, "D") = "及格"
            Case Else
                Cells(i, "D") = "不及格"
        End Select
        
    Next i

End Sub

结果:


 

转载:https://www.lanrenexcel.com/vba-program-select-structure/