In excel/VBA I have this code
Dim colName as Variant
Dim lengthToDispl as Integer
colName = Array("A", "B", "C")
lengthToDispl = colName.length
I get the following error 'Object Required'. It relates to the last line.
How do I assign the length of an array of variable length (containing strings) to a variable (integer)?
The function you want to return the 'size' of the array is the UBound function which returns the Upper Boundary. This is often used with its counterpart, the LBound function which returns the Lower Boundary.
This may or may not be returning the number you are looking for. Some arrays are arranged with a zero-based index and some have a one-based index. It depends on the way that they are declared and assigned.
The above creates an array with a zero-based index and three elements in position
colName(0)
,colName(1)
andcolName(2)
. The UBound (e.g.UBound(colName)
) will return 2, not 3. To cycle through it, use both LBound and UBound.When assigning values from a worksheet's cells, you get a one-based, two dimensioned array, even if you are only collecting the values from a single column or row. The other dimension or Rank is simply 1 to 1.
This creates a two-dimensioned array with a one-based index as in
ReDim colName (1 to 2, 1 to 3)
.I recommend using both LBound and UBound when dealing with the elements of an array.