VB中的IF語句使用詳解

VB中的if條件語句其實可以用翻譯來配上去的,if在這裡就是"如果/判斷". then在這裡就是"接著".else在這裡就是"相反"..end if在這裡就是"結束判斷"


VB中的IF語句使用詳解


比如例子:
if text1.text = "ok" then ' 如果text1.text裡面的內容是"ok" 那麼就執行下列代碼
msgbox "文本框裡的內容是ok"
else '相反,如果text1.text裡面的內容不是"ok", 那麼就執行下列代碼
msgbox "文本框裡的內容不是ok"
end if


其中,代碼有換行就要用End If,當不換行就需要End If
例如:
例一:
If xxxx Then yyyy '這時就不用也不可以用End If
例二:
If xxxx Then
yyyy
End If '這時就必須要用End If


假如你希望選擇多套代碼之一來執行,可以使用if...then...elseif語句

<code>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
/<code>

Select Case


假如你希望選擇多套代碼之一來執行,可以使用 SELECT 語句

<code>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
/<code>

以上代碼的工作原理:首先,我們需要一個簡單的表達式(常常是一個變量),並且這個表達式會被做一次求值運算。然後,表達式的值會與每個 case 中的值作比較,如果匹配,被匹配的 case 所對應的代碼會被執行。


IF語句也可以寫成嵌套的形式:

<code>if   then/<code>
<code>else/<code>
<code>if   then/<code>
<code>else/<code>


分享到:


相關文章: