Arrays

Top  Previous  Next

Creating arrays

 

NativeVB allows to create single-dimensional arrays as well as multi-dimensional arrays using Dim or ReDim statements, specifying the array length in round brackets. For example:

 
Dim a(5);   'Single-dimensional array.

Dim b(7, 3); 'Multi-dimensional array.

 

The low bound of the array is always zero in NativeVB. ReDim statement allows to change the length of the array:

 

Dim a(5)

ReDim a(10)

 

The ReDim statement does not declare the variable. The variable used in ReDim statement should be previously declared using Dim statement. also, ReDim statement does not allow to change the count of array dimensions as well as array element type. The keyword Preserve can be used to specify that the current content of the array should be preserved while resizing:

 

Dim a(5)

a(0) = 3

ReDim Preserve a(10)

MsgBox(a(0))

 

NativeVB supports creation of the arrays with elements of type other than varVariant. For example, it is possible to create an array with elements of varByte for more efficient data storage:

 

Dim a(5) As Byte

 

Following table specifies the list of type names that can be used in array constructor:

 

Type name

Variant value type code

Integer

varInteger

String

varOleStr

Double

varDouble

Single

varSingle

Boolean

varBoolean

Variant

varVariant

Byte

varByte

Word

varWord

LongWord

varLongWord

SmallInt

varSmallInt

Currency

varCurrency

ShortInt

varShortInt

Int64

varInt64

UInt64

varUInt64

Error

varError

Object

varDispatch

 

If the type name is omit, the array will be created with varVariant element type.

 

Using arrays

 

The script program should use round bracket syntax to access array elements, just like in MS VBScript:

 

Dim a(10)

a(0) = 5

a(1) = 7

 

Dim b(5, 7)

b(1, 3) = 11;

 

Y = a(0) + a(1) + b(1, 3)

 

The LBound and UBound intrinsic functions can be used to determine the low and hight bounds of the array. For multi-dimensional arrays the dimension number can be specified as a second argument:

 

Dim a(10)

For i = LBound(a) To UBound(a)

  a(i) = i + 100

Next

 

Dim a(10, 2)

For i = LBound(a, 1) To UBound(a, 1)

  For j = LBound(a, 2) To UBound(a, 2)

    a(i, j) = i + j + 100

  Next

Next

 

Array function

 

For creation of a single-dimensional array from a list of values the Array intrinsic function can be used. Specify array element values as arguments in the Array function call:

 

Dim x = Array(1, 2, 3, 4, 5)