VBScript 程式設計:控制結構 (Control Structure)

PUBLISHED ON SEP 2, 2018 — PROGRAMMING

VBScript 提供四種程式語言中常見的控制結構:

  • 選擇 (selection)
    • If
    • Select
  • 迭代 (iteration),又稱迴圈 (loop)
    • While
    • For

以下短例使用 If 敘述:

Max = 1
Min = -1

Randomize
Ans = Int((Max - Min + 1) *Rnd + Min)

If Ans > 0 Then
	Wscript.Echo Ans & " is larger than 0"
ElseIf Ans < 0 Then
	Wscript.Echo Ans & " is smaller than 0"
Else
	Wscript.Echo Ans & " is equal to 0"
End If

以下短例使用 Select 敘述:

註:Select 相當於 C 家族的 switch

dtmToday = Date()

dtmDayOfWeek = DatePart("w", dtmToday)

Select Case dtmDayOfWeek
    Case 1 Wscript.Echo "Sunday"
    Case 2 Wscript.Echo "Monday"
    Case 3 Wscript.Echo "Tuesday"
    Case 4 Wscript.Echo "Wednesday"
    Case 5 Wscript.Echo "Thursday"
    Case 6 Wscript.Echo "Friday"
    Case 7 Wscript.Echo "Saturday"
End Select

以下短例使用 While 敘述:

i = 1
While i <= 10
	Wscript.Echo i
	i = i + 2
Wend

以下短例的 For 敘述使用計數器 (counter):

For i = 1 to 10 Step 2
	Wscript.Echo i
Next

至於使用集合的 For Each 留待陣列的章節再說明。

comments powered by Disqus