array in excel vba code example

Example 1: vba array from worksheet data

'In Excel VBA, the quickest way to pull data from a worksheet into a VBA array
'is to do it all at once:

Dim v As Variant
v = Range("a1:b20").Value

'Please note that, here, 'v' is a scalar variable of type Variant. Scalar means
'that 'v' is NOT an array. But interestingly in this case, 'v' can be 
'treated exactly like an array. To understand why, please keep reading...

'Variant variables can be assigned many types of values, for example, 
'all of the following (and many others) are valid:

v = 123
v = 12.19971
v = "abcdefg"
Set v = New Collection

'IN ADDITION, a Variant can also be assigned an entire array, dynamic or static:

Dim v As Variant, arr() As Long
  
ReDim arr(1 to 4)
arr(1) = 11
arr(2) = 12
arr(3) = 13
arr(4) = 14
  
v = vArrA
  
'Now that the array of Longs 'arr' has been assigned to the Variant 'v', we can
'access the elements directly from 'v':
  
MsgBox v(4)		'<--displays: 14
  
'A very efficient way to read data from a worksheet range is to directly assign
'the data to a Variant by having that variable point to an array of Variants:
 
v = Sheet1.Range("a1:b20").Value
  
'The 'Value' property of the Range object creates a 2D array of Variant 
'elements the same size as the specified range, in this case,
'20 rows of 2 columns, with a lower bound of 1 for both array dimensions.
'Here, we assign that array directly to the scalar Variant 'v', all in one go. 
'The scalar Variant 'v' can now be treated as an array, even though it is 
'actually a scalar variable that points to an array THAT WAS NEVER NAMED:
  
MsgBox v(2, 20) 	'<--displays: the value that was in Sheet1, cell B20
  
'As long as the worksheet range consists of more than one cell, this method
'always results in an array and that array is always 2D. It is never 1D.

'If the range consists of only ONE cell, then this method does NOT create an
'array; instead, it assigns that one cell's scalar value to the Variant 'v'.
'This one-cell treatment must bo gaurded against.
  
'However, this shortcut method of copying Excel ranges to VBA arrays is
'very convienent and its use is common. The advantage is not only
'extremely concise code; this technique is much faster than copying
'cell-by-cell... and the speed improvement grows with the size of
'the range being copied.

'The code can even be shortened:
  
v = [Sheet1!a1:b20]
  
'The square brackets are a shorthand notation for VBA's Evaluate() function.
'This shorthand produces exactly the same results as the previous example,
'because the Evaluate() function returns a Range object in this instance and
'the default property of the Range object is the 'Value' property.

'In the above examples, the Range object is returning its 
'default... the Range.Value property. But keep in mind that the
'Range.Value2 property is roughly 20% quicker. So it slightly more
'performant to code these two examples like so:

v = [Sheet1!a1:b20].Value2
v = Sheet1.Range("a1:b20").Value2
  
'Important: the array created using the 'Value' or 'Value2' properties
'           is completely detached from the source range on the
'           worksheet. Either can be updated and the changes will NOT 
'           affect the other.


'Note: VBA utilizes the OLE/COM SAFEARRAY data structure for its
'      array implementation:
  
'      https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oaut/2e87a537-9305-41c6-a88b-b79809b3703a
' 	   https://ecs.syr.edu/faculty/fawcett/Handouts/cse775/presentations/BruceMcKinneyPapers/safeArrays.htm
'	   http://www.roblocher.com/whitepapers/oletypes.html
'
'
'

Example 2: vba string array

'In VBA a dynamic string array is declared in the following ways:

Dim strArr1() As String
Dim strArr2$()

'Neither declaration style is prefered. They are exactly equivalent.

'Both ways above produce a dynamic array, which means that the exact size of
'the array (how many elements) is specified later in code:

Redim strArr1(1 to 10)

'To instead declare a static string array (an array with a fixed size), 
'specify the size within the Dim statement:

Dim strArr1(1 to 10) As String
Dim strArr2$(0 to 4)

'ReDim() cannot later be used on static arrays. Their size is fixed.

'Once a string array is declared, the array elements are assign one at a time:

strArray1(1) = "abc"

'However, the Split() function can be used to split a string and assign to and
'to also size a dynamic string array in one go:

Dim strArr3$()
strArray3 = Split("a,b,c", ",")

'strArray3 will now contain three elements, "a", "b", and "c".

'Note: String arrays can only conatin text values. When numbers are assigned
'      to string array elements, the number is first coerced to a string value.
'      Boolean and Date values are likewise coerced to text values.
'      Objects CANNOT be assinged to string array elements.
'
'      For the above reasons (and especially with Excel data) it may be better
'      to declare and use Variant arrays instead of String arrays. Variants
'      can be assigned any data type. The trade-off is that manipulating 
'      Variants is slightly slower than base data types.
'
'      Variants are the default data type in VBA so the following declares
'      an array of Variants:

Dim vArr1()

'      But the data type may also be specified explicitly:

Dim vArr1() As Variant

'      The Variant data type does not have a specific Type Declaration Character.
'      For example, the String data type has the '$' type declaration character
'      which was demonstrated at the top of this page. But since the Variant is
'      VBA's default, no type declaration character is needed. Not specifying
'      a type results in a variable's type being a Variant, by default.

'Note: it is important to realize that since a Variant can hold any other type
'      of data, it can also hold an array. It is EXTREMELY common in VBA to 
'      declare a single Variant variable that will later be assinged an array:

Dim v

'	   The above variable is a single Variant. It is not an array. Variants
'      can be assinged numbers, dates, Booleans, error values, objects, 
'      essentially anything. And in addition, variants can also
'      be assigned arrays of any type:

v = Array(1, 2, 3, "a", "b", "c", True, False, #1/1/2021#)

'      The above line creates an array of 9 Variant values and assigns the 
'      entire array to the Variant existing variable, 'v'.
'
'      Perhaps the most common way to assign an array of Variants to 
'      an existing Variant variable is to pull data from a worksheet range:

v = Sheet1.Range("A1:A10").Value

'      The above statement assigns a 2-dimension array to v, ten rows deep 
'      and one column wide. The values and data types of the 
'      ten elements will correspond to the values and types
'      in the Sheet1 range, A1:A10. It is important to realize that 
'      the VBA array created here is a copy of the data in the worksheet
'      range. Changing one does not affect the other. But it is possible
'      to write the VBA array back to Excel to the original range, or 
'      to any range in any worksheet in any open workbook.
'
'
'

Example 3: excel vba reset array to zeros fastest way

'In VBA to reset a dynamic array of Longs or Doubles to all zeros, the simplest way 
'is to use the Redim() function. It's also extremely fast, roughly four times 
'faster than iterating over the array to set each element.

Sub Test_ArrayZeroing()
  	Dim i&, k&, a() As Long
    Dim time1#, time2#

    k = 100000000						'<--100 million elements
    ReDim a(1 To k)
    For i = 1 To k: a(i) = i: Next      '<--Fill array

    time1 = Timer
		'For i = 1 To k: a(i) = 0: Next '<--Method 1: 1125 ms
		ReDim a(1 To k)                 '<--Method 2:  260 ms (easy and faster)
    time2 = Timer
    
    Debug.Print "Test_ArrayZeroing: " & (time2 - time1) * 1000
End Sub


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'If you are willing to use an external call to Windows then an much faster
'method exists:

Private Declare PtrSafe Sub AssignZero Lib "kernel32" Alias "RtlZeroMemory" (pDst As Any, Optional ByVal CB& = 4)

Sub Test_ArrayZeroing()
    Dim i&, k&, a() As Long
    Dim time1#, time2#

  	k = 100000000						'<--100 million elements
    ReDim a(1 To k)
    For i = 1 To k: a(i) = i: Next      '<--Fill array

    time1 = Timer
        'For i = 1 To k: a(i) = 0: Next '<--Method 1: 1125 ms
        'ReDim a(1 To k)                '<--Method 2:  260 ms
		AssignZero a(1), k * 4          '<--Method 3:   74 ms (super fast)
    time2 = Timer
    
    Debug.Print "Test_ArrayZeroing: " & (time2 - time1) * 1000
End Sub

'Note that when using AssignZero() with an array of Doubles, remember that
'Doubles require 8 bytes of memory each, as opposed to the 4 bytes required
'for Longs.

'So the call to AssinZero() would like this for and array of Doubles:
AssignZero a(1), k * 8

'Note that the first argument of AssignZero() should be the first element
'of the array to be reset to zeros. The lowerbound in the above examples is 1, 
'but your array may have a lowerbound of 0... or some other number.

'Note that all three methods here work for arrays of Longs and Doubles. But to
'zero out an array of Variants, the only option is Method 1. This is because
'the default value for a Variant is EMPTY, not zero... and AssignZero() will
'not work because Variants store and require metadata in addition to 
'the value... and that metadata would be wiped out by AssignZero().

'Note that to reset an array to some value other than zero, the only
'option is to use Method 1.

'Note that this entire post is about Dynamic arrays. If you wish to zero out a Static
'array of Longs or Doubles you may also use the 'Erase' statement:
Erase a

'
'
'

Example 4: vba array

'VBA arrays can be fixed-size (static) or resizable (dynamic).
'This is determined when the array is declared:
Dim vArrA()			'dynamic: size is determined later.
Dim vArrB(1 to 5)	'static:  size is determined now and cannot be changed.

'Array size refers to the number of elements in the array. For example, vArrB()
'above has five elements. The "1 to 5" is referred to as the array's range of
'indices. The range size must be positive, meaning the number of elements must 
'be positive. This means that the 2nd integer in the range must be greater 
'or equal to the first integer.

'VBA is unusual among programming languages with regards to the lowerbound or 
'the base, of arrays. Most languages require arrays to have a base (or lowerbound)
'of zero. VBA arrays can have lowerbounds of ANY Long Integer value
'(-2147483648 through +2147483647). So, all of the following are valid:

Dim vArrC(0 to 9)
Dim vArrD(1 to 10)
Dim vArrE(11 to 20)
Dim vArrF(-8877 to -8868)
Dim vArrG(-5 to 4)

'vArrC through vArrG are perfectly legal and each has precisely 10 elements. Note
'that the size AND the bounds are fixed for static arrays. Both of these
'attributes can be changed for dynamic arrays whenever the need arises:

ReDim vArrA(1 to 1000)

'And at a later point:

ReDim vArrA(0 to 4)

'A third attribute of VBA arrays is the number of dimensions. Every example on
'this page thus far represents a 1D array. Another term for a one-dimensional
'array is vector. A vector does not really have rows or columns, just
'elements.

'However, when writing a 1D array to a worksheet, Excel treats the array as if 
'it were a 2D array consisting of 1 row and n colums (where n is equal to the
'number of elements). This fact causes confusion for many.
'Consider:

ReDim vArrA(1 to 5)
vArrA(1) = "m"
vArrA(2) = "n"
vArrA(3) = "o"
vArrA(4) = "p"
vArrA(5) = "q"
Sheet1.Range("A1:E5") = vArrA

'Sheet1 now has the following values:
'    A   B   C   D   E
'1   m   n   o   p   q
'2   m   n   o   p   q
'3   m   n   o   p   q
'4   m   n   o   p   q   
'5   m   n   o   p   q

'This is why Transpose() is required to write the 1D array vertically:

Sheet1.Range("A1:E5") = WorksheetFunction.Transpose(vArrA)

'Sheet1 now has the following values:
'    A   B   C   D   E
'1   m   m   m   m   m
'2   n   n   n   n   n
'3   o   o   o   o   o
'4   p   p   p   p   p   
'5   q   q   q   q   q

'Notice that the one array with five elements can be written to multiple rows
'or with Transpose() to multiple columns. Of course, the array can be 
'written to one row:
Sheet1.Range("A1:E1") = vArrA

'Or to one column:
Sheet1.Range("A1:A5") = WorksheetFunction.Transpose(vArrA)

'Since Excel treats 1D arrays (vectors) oddly when writing to a worksheet, it
'can be easier to work with 2D arrays. In Excel VBA, 2D arrays are row major.
'This means that rows are represented by the first dimension and columns are 
'represented by the second.

ReDim vArrA(1 to 5, 1 to 10)
'            ^rows   ^cols

'vArrA is now sized as a 2D array with 5 rows of 10 columns. It can be written
'to a worksheet with 5 rows of 10 columns without using Transpose().

'Size, lower and upper bounds, and number of dimensions 
'are all fixed for static arrays and they are all specified when the array is 
'declared:

Dim vArrH(0 to 9, 1 to 10)

'vArrH is a static 2D array of 100 elements, 10 rows of 10 columns, with
'0 as the lowerbound for the first dimension (the rows) and 1 as the lowerbound
'of the second dimension (the columns). None of these attributes can later
'be changed for vArrH, since it is a static (or fixed) array. In contrast,
'all three of these attributes can be changed for a dynamic array... at any time.

'The max number of dimensions supported for an array is 60, though
'it is unusual to use arrays with more than 3 dimensions. Conceptually, a
'1D array is a vector, a 2D array can be thought of as a worksheet with rows
'and columns, a 3D array can be thought of as a workbook with multiple
'worksheets (or a cube), and a 4D array can be thought of a folder of workbooks 
'(or perhaps a hypercube). But keep in mind that each dimension can be declared
'with a different number of elements. For example, a 4D dynamic array:

ReDim vArrA(0 to 4, 1 to 10, 3 to 7, 1 to 2)
'           ^rows   ^cols    ^sheets ^books

'A fourth attribute of arrays is the data type. VBA's default data type
'is the Variant. If no data type is specified then by default the data type is actually Variant. So all the
'examples so far are Variant arrays, that is an array where every single element
'is of data type Variant.

'Here are some other data type array examples. They can be written verbosely
'or in some cases with a type declaration character:

Dim a() As Double   'or... Single, Short, Long, Currency, String, Byte, Date
					'or... Boolean, UserDefinedType, ClassName, Object

Dim a#()			'or... a!(), a%(), a&(), a@(), a$()

'Note: 64bit VBA also includes the LongLong data type:
Dim a() As LongLong 'or... a^()

Tags:

Vb Example