ReDim 语句

声明动态数组变量,并在过程级别分配或重新分配存储空间。

语法

ReDim [Preserve] varname(subscripts) [, varname(subscripts)] . . .

参数:

  • Preserve:更改最后一个维的大小时,保留现有数组中的数据。

  • Varname:变量的名称;遵循标准变量命名约定。

  • Subscripts:数组变量的维。

注释

ReDim 语句用于调整已使用带有空括号(没有维下标)的 Private、Public 或 Dim 语句正式声明的动态数组的大小。可以重复使用 ReDim 语句来更改数组中的元素和维数。

如果使用 Preserve 关键字,则只能调整最后一个数组维的大小,并且根本无法更改维数。例如,如果数组只有一个维,则可以调整该维的大小,因为它是最后一个也是唯一一个维。但是,如果数组具有两个或更多维,则只能更改最后一个维的大小,并仍保留数组的内容。

以下示例说明如何增加动态数组的最后一个维的大小,而不清除数组中包含的任何现有数据。

示例 1:基本 ReDim 用法(无 Preserve)

Dim arr()
' Initially, create an array with 3 elements
ReDim arr(2)  ' Array can hold 3 elements (0, 1, 2)
' Assign values to the array
arr(0) = "Apple"
arr(1) = "Banana"
arr(2) = "Cherry"
' Now, resize the array to hold 5 elements
ReDim arr(4)  ' Array can hold 5 elements (0, 1, 2, 3, 4)
'If you try to access indexes 0, 1, 2 there will be no values.
' The previous values are lost because we did not use Preserve
arr(3) = "Date"
arr(4) = "Elderberry"

示例 2:使用 ReDim Preserve 保留现有数据

Dim arr()
' Initially, create an array with 3 elements
ReDim arr(2)  ' Array can hold 3 elements (0, 1, 2)
' Assign values to the array
arr(0) = "Apple"
arr(1) = "Banana"
arr(2) = "Cherry"
' Now, resize the array to hold 5 elements, keeping the existing data
ReDim Preserve arr(4)  ' Array can hold 5 elements (0, 1, 2, 3, 4)
' The previous values are preserved, so we can add more elements
arr(3) = "Date"
arr(4) = "Elderberry"

警告:如果使数组小于最初的数组,则已清除元素中的数据将丢失。

初始化变量时,数字变量初始化为 0,字符串变量初始化为零长度字符串 ("")。必须先使用 Set 语句为引用对象的变量赋予现有对象,然后才能使用它。在为它赋予对象之前,声明的对象变量具有特殊值 Nothing。