If...Then...Else 陳述式 (Visual Basic)

根據運算式的值而定,有條件地執行陳述式群組。

語法

' Multiline syntax:
If condition [ Then ]
    [ statements ]
[ ElseIf elseifcondition [ Then ]
    [ elseifstatements ] ]
[ Else
    [ elsestatements ] ]
End If

' Single-line syntax:
If condition Then [ statements ] [ Else [ elsestatements ] ]

本文包含數個範例,說明如何使用 If...Then...Else 陳述式:

組件

condition
必要。 運段式。 必須評估為 TrueFalse,或是評估為隱含轉換成 Boolean 的資料類型。

如果運算式是評估為 Nothing可為 NullBoolean 變數,則會將條件當作運算式為 False 來處理,如果存在 ElseIf 區塊,則予以評估,如果存在 Else 區塊,則予以執行。

Then
在單行語法中為必要;在多行語法中為選擇性。

statements
選擇性。 如果 condition 評估為 True,則會執行接在 If...Then 後面的一或多個陳述式。

elseifcondition
如果 ElseIf 存在,則為必要。 運段式。 必須評估為 TrueFalse,或是評估為隱含轉換成 Boolean 的資料類型。

elseifstatements
選擇性。 如果 elseifcondition 評估為 True ,則會執行接在 ElseIf...Then 後面的一或多個陳述式。

elsestatements
選擇性。 如果先前的 conditionelseifcondition 運算式都未評估為 True,則會執行一或多個陳述式。

End If
終止 If...Then...Else 區塊的多行版本。

備註

多行語法

遇到 If...Then...Else 陳述式時,就會測試 condition。 如果 conditionTrue,則會執行接在 Then 後面的陳述式。 如果 conditionFalse,則會依序評估每個 ElseIf 陳述式 (如果有的話)。 找到 Trueelseifcondition 時,即會執行緊接在相關聯 ElseIf 之後的陳述式。 如果沒有 elseifcondition 評估為 True ,或者如果沒有 ElseIf 陳述式,則會執行接在 Else 後面的陳述式。 執行接在 ThenElseIfElse 後面的陳述式之後,會繼續執行接在 End If 後面的陳述式。

ElseIfElse 子句都是選擇性的。 您可以視需要在 If...Then...Else 中擁有許多 ElseIf 子句,但 ElseIf 子句不能出現在 Else 子句之後。 If...Then...Else 陳述式可以彼此巢狀。

在多行語法中,If 陳述式必須是位於第一行的陳述式。 ElseIfElseEnd If 陳述式只能在前面加上行標籤。 If...Then...Else 區塊的結尾必須是 End If 陳述式。

提示

當您評估具有數個可能值的單一運算式時,Select...Case 陳述式可能會更有用。

單行語法

您可以針對單一條件使用單行語法,其中包含條件為 true 時所要執行的程式碼。 不過,多行語法提供更多結構和彈性,且更容易閱讀、維護及偵錯。

檢查 Then 關鍵字後面的內容,以判斷陳述式是否為單行 If。 如果同一行 Then 之後出現註解以外的任何其他內容,就會將該陳述式視為單行 If 陳述式。 如果 Then 不存在,則必須是多行 If...Then...Else 的開頭。

在單行語法中,您可以執行多個陳述式作為 If...Then 決定的結果。 所有陳述式都必須在同一行,並以冒號分隔。

多行語法範例

下列範例說明如何使用 If...Then...Else 陳述式的多行語法。

'Create a Random object to seed our starting value 
Dim randomizer As New Random()
'set our variable
Dim count As Integer = randomizer.Next(0, 5)

Dim message As String

'If count is zero, output will be no items
If count = 0 Then
    message = "There are no items."
    'If count is 1, output will be "There is 1 item.".        
ElseIf count = 1 Then
    message = "There is 1 item."
    'If count is greater than 1, output will be "There are {count} items.", where {count} is replaced by the value of count. 
Else
    message = $"There are {count} items."
End If

Console.WriteLine(message)

'This example displays output like the following:
' There are 4 items.

巢狀語法範例

下列範例包含巢狀 If...Then...Else 陳述式。

Public Sub Main()
    ' Run the function as part of the WriteLine output.
    Console.WriteLine("Time Check is " & CheckIfTime() & ".")
End Sub

Private Function CheckIfTime() As Boolean
    ' Determine the current day of week and hour of day.
    Dim dayW As DayOfWeek = DateTime.Now.DayOfWeek
    Dim hour As Integer = DateTime.Now.Hour

    ' Return True if Wednesday from 2 to 3:59 P.M.,
    ' or if Thursday from noon to 12:59 P.M.
    If dayW = DayOfWeek.Wednesday Then
        If hour = 14 Or hour = 15 Then
            Return True
        Else
            Return False
        End If
    ElseIf dayW = DayOfWeek.Thursday Then
        If hour = 12 Then
            Return True
        Else
            Return False
        End If
    Else
        Return False
    End If
End Function

'This example displays output like the following:
'Time Check is False.

單行語法範例

下列範例說明如何使用單行語法。

Private Sub SingleLine()

    'Create a Random object to seed our starting values 
    Dim randomizer As New Random()

    Dim A As Integer = randomizer.Next(10, 20)
    Dim B As Integer = randomizer.Next(0, 20)
    Dim C As Integer = randomizer.Next(0, 5)

    'Let's display the initial values for comparison
    Console.WriteLine($"A value before If: {A}")
    Console.WriteLine($"B value before If: {B}")
    Console.WriteLine($"C value before If: {C}")

    ' If A > 10, execute the three colon-separated statements in the order
    ' that they appear
    If A > 10 Then A = A + 1 : B = B + A : C = C + B

    'If the condition is true, the values will be different
    Console.WriteLine($"A value after If: {A}")
    Console.WriteLine($"B value after If: {B}")
    Console.WriteLine($"C value after If: {C}")

End Sub

'This example displays output like the following:
'A value before If: 11
'B value before If: 6
'C value before If: 3
'A value after If: 12
'B value after If: 18
'C value after If: 21

另請參閱