声明数组变量有几种不同的方法。第一种方法是使用空的圆括号显式指定数组类型:
'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
通过用逗号分隔变量声明,可以在单个语句中声明几个变量。