有數種宣告陣列變數的方法。第一種方法是使用空白的括號,並明確指定陣列的型別:
'Declare x to be a Global variable 'of Number Array type Global x () As Number 'Initialize x x = Array (10, 20, 30) 'Declare y to be a Shared variable 'of String Range Array type Shared y () As String Range 'Initialize y y = Array ("A" To "C", "H" To "J")
第二種方法是宣告變數,但不將該變數指定為陣列,也不指定型別,而等待變數的第一次指派工作完成型別的指定工作:
'Declare y to be a Local variable 'but do not specify its type Dim y 'The type of y is now set to be a String Array y = Array ("Sun", "Mon", "Tue", "Wed", "Th", _ "Fri", "Sat")
第三種方法是將變數宣告為陣列,但不完全指定其型別,等待第一次指派工作來指定型別。持續上述 y 的宣告:
'Declare z to be a Local variable that is an Array Local z() 'z is set to Array ("Mon", "Tue") and is a String Array z = y(2 to 3)
第四種方法是在宣告變數時,明確地指定陣列的大小。如果使用這種技巧,陣列會自動建立,且用預設值填滿。例如,以數字陣列而言,每個元素都會初始化為 0;而如果是字串陣列,則每個元素都會初始化為空白的字串 ""。因為這種宣告方式會確實建立陣列,所以必須使用 As 子句來指定其型別,以供 Crystal Reports 判斷該陣列需要多少儲存空間。
Dim a(2) As String 'Assign a value to the first element of the array a a(1) = "good" a(2) = "bye" 'The & operator can be used to concatenate strings 'the formula returns the String "goodbye" formula = a(1) & a(2)
您可以指派陣列元素的值,也可以用這些值來進行其他計算。
Global x() As String x = Array ("hello", "bye", "again") 'Now x is Array ("hello", "once", "again") x (2) = "once" 'The statement below would cause an error if not 'commented out since the array has size 3 'x (4) = "zap" 'The formula returns the String "HELLO" formula = UCase (x (1))
Redim 和 Redim Preserve 關鍵字可以用來重調陣列的大小,這對於在陣列中加入額外資訊很有用。Redim 會在調整陣列的大小之前,先清除陣列中原來的內容,而 Redim Preserve 則會保存原來的內容。
Dim x () As Number Redim x (2) 'Now x is Array (0, 0) x (2) = 20 'Now x is Array (0, 20) Redim x (3) 'Now x is Array (0, 0, 0) x (3) = 30 'Now x is Array (0, 0, 30) Redim Preserve x (4) 'Now x is Array (0, 0, 30, 0) formula = "finished"
陣列常與 For/Next 迴圈一起使用。下列的範例中使用 For/Next 迴圈來建立並使用陣列 Array (10, 20, 30, ..., 100)
。
Dim b (10) As Number Dim i For i = 1 To 10 b(i) = 10 * i Next i formula = b(2) 'The formula returns the Number 20
可以在單一的陳述式中宣告數個變數,只要宣告之間以逗號相隔即可。