VBA String Array

A string array in VBA can be created by using Dim as follows:

Create and access a string array in VBA – one dimensional

A string array in VBA can be created by using Dim keyword as follows:

Dim str_arr(7) As String

Its index starts at 0.

Or

Dim str_arr(3 To 10) As String

Its index starts at 3

Accessing string array element

The following VBA program creates and accesses a string array and its elements. Then we displayed an element value in the message box:

Output:

VBA-string-array

An example declaring an array with “To”

Now we declared the string same array with (3 To 10) syntax.

Code:

Output:

VBA-string-array-2

 

Accessing all array elements by For..Each loop

The VBA For Each loop can be used to iterate through each array element. The example below creates a string array.

A For..each loop is used to iterate through each array element.

Then we collect all array values in a string variable and display the result in a message box.

VBA code:

Result:

VBA-string-array-for..

A two-dimensional string array example

A 2-D string array can be created by using the Dim keyword as follows:

Dim str_arr_2d(1 To 5, 1 To 3) As String

The example below creates a two-dimensional array and accesses one element and displays in the message box.

Code:

Output:

VBA-string-array-2-d

Creating a two-dimensional string array based on Excel cells data

In this example, we will create two dimensional array from the range of cells in Excel. For that we have the following sample sheet:

string-array-excel

VBA Code

Result:

string-array-cells

How did it work?

  • A 2-D array of string type is created
  • Outer for loop is used to run from 2 to 8 indices (representing the first dimension of the array)
  • The inner loop executed from 2 to 5 (second dimension of the array)
  • In each iteration, the element is assigned the value from the cell
  • In the message box, we displayed (4, 2) array item, which is row number 4 and column 2

Get the size of above string array

So, how many elements do we have in our above array?

Either count them one by one or use the LBound and UBound functions of the array.

The program below uses these functions to get the size of our Excel-based array:

Output:

string-array-length

 

Display the whole 2-D string array in the message box

Result:

string-array-display-2