Visual Basic 6.0 使用者可用的變數範圍
更新:2007 年 11 月
Visual Basic 2008 更新了區域變數範圍來支援區塊範圍,並增進結構化的程式設計。
Visual Basic 6.0
在 Visual Basic 6.0 中,在程序內部宣告的任何變數都有一個程序範圍,如此它就能在相同程序內的任何地方被存取。如果變數是在區塊 (也就是一組以 End、Loop 或 Next 結束的陳述式) 內被宣告,則在區塊外部仍可以存取變數。
下列範例說明了程序範圍,其中的區塊為 For 迴圈 (Loop):
For I = 1 To 10
Dim N As Long = 0
' N has procedure scope although it was declared within a block.
N = N + Incr(I)
Next I
W = Base ^ N
' N is still visible outside the block it is declared in.
Visual Basic 2005
在 Visual Basic 2008 中,在區塊內部宣告的變數擁有區塊範圍,而且不能在區塊外部存取該變數。以上範例可以重寫如下:
Dim N As Long = 0
' N is declared outside the block and has procedure scope.
For I As Integer = 1 To 10
' I is declared by the For statement and therefore within the block.
N = N + Incr(I)
Next I
w = Base ^ N
' N is visible outside the block but I is not.
因為 For 陳述式將 I 宣告為 For 區塊的一部分,因此 I 僅具有區塊範圍。
但是,變數的存留期 (Lifetime) 還是代表整個程序的存留期。不論變數有區塊範圍或程序範圍都是如此。如果您是在區塊內部宣告變數,而且如果您在程序存留期間輸入該區塊很多次,您應該要初始化變數來避免未預期的值。