Syntax
ReDim [
Preserve]
varname(subscripts) [
As type] [
, varname(subscripts) [
As type]]
. . .
The
ReDim statement syntax has these parts:
PartDescription
PreserveOptional.
Keyword used to preserve the data in an existing
array when you change the size of the last dimension.
varnameRequired. Name of the variable; follows standard variable naming conventions.
subscriptsRequired. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The
subscripts argument uses the following syntax: [
lower To]
upper [
,[
lower To]
upper]
. . .
When not explicitly stated in
lower, the lower bound of an array is controlled by the
Option Base statement. The lower bound is zero if no
Option Base statement is present.
typeOptional.
Data type of the variable; may be
Byte,
Boolean,
Integer,
Long,
Currency,
Single,
Double,
Decimal (not currently supported),
Date,
String (for variable-length strings),
String *
length (for fixed-length strings),
Object,
Variant, a
user-defined type, or an
object type. Use a separate
As type clause for each variable being defined. For a
Variant containing an array,
type describes the type of each element of the array, but doesn't change the
Variant to some other type.
Remarks
The
ReDim statement is used to size or resize a dynamic array that has already been formally declared using a
Private,
Public, or
Dim statement with empty parentheses (without dimension subscripts).
You can use the
ReDim statement repeatedly to change the number of elements and dimensions in an array. However, you can't declare an array of one data type and later use
ReDim to change the array to another data type, unless the array is contained in a
Variant. If the array is contained in a
Variant, the type of the elements can be changed using an
As type clause, unless you’re using the
Preserve keyword, in which case, no changes of data type are permitted.
If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all. (
Nếu dùng từ khóa Preserve ta chỉ có thể thay đổi giá trị ở chiều cuối cùng của mảng, và không được phép thay đổi số chiều). For example, if your array has only one dimension, you can resize that dimension
because it is the last and
only dimension. However, if your array has two or more dimensions, you can change the size of
only the last dimension and still preserve the contents of the array. The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.
ReDim X(10, 10, 10). . .ReDim Preserve X(10, 10, 15)Similarly, when you use
Preserve, you can change the size of the array only by changing the upper bound; changing the lower bound causes an error.