Is it possible to either:
-
Declare an array as a constant
OR
-
Use a workaround to declare an array that is protected from adding, deleting or changing elements, and therefore functionally constant during the life of a macro?
Of course I could do this:
Const myConstant1 As Integer = 2
Const myConstant2 As Integer = 13
Const myConstant3 As Integer = 17
Const myConstant4 ...and so on
…but it loses the elegance of working with arrays. I could also load the constants into an array, and reload them each time I use them, but any failure to reload the array with those constant values before use could expose the code to a «constant» value that has changed.
Any workable answer is welcome but the ideal answer is one that can be setup once and not require any changes/maintenance when other code is modified.
asked Dec 8, 2016 at 18:15
You could use a function to return the array and use the function as an array.
Function ContantArray()
ContantArray = Array(2, 13, 17)
End Function
answered Dec 8, 2016 at 18:32
11
How about making it a function? Such as:
Public Function myConstant(ByVal idx As Integer) As Integer
myConstant = Array(2, 13, 17, 23)(idx - 1)
End Function
Sub Test()
Debug.Print myConstant(1)
Debug.Print myConstant(2)
Debug.Print myConstant(3)
Debug.Print myConstant(4)
End Sub
Nobody can change it, resize it, or edit its content… Moreover, you can define your constants on just one line!
answered Dec 8, 2016 at 18:22
A.S.HA.S.H
29k5 gold badges22 silver badges49 bronze badges
I declared a String
constant of "1,2,3,4,5"
and then used Split
to create a new array, like so:
Public Const myArray = "1,2,3,4,5"
Public Sub createArray()
Dim i As Integer
A = Split(myArray, ",")
For i = LBound(A) To UBound(A)
Debug.Print A(i)
Next i
End Sub
When I tried to use ReDim
or ReDim Preserve
on A
it did not let me. The downfall of this method is that you can still edit the values of the array, even if you can’t change the size.
answered Dec 8, 2016 at 18:21
SoulfireSoulfire
4,21821 silver badges32 bronze badges
2
If the specific VBA environment is Excel-VBA then a nice syntax is available from the Excel Application’s Evaluate method which can be shortened to just square brackets.
Look at this
Sub XlSerialization1()
Dim v
v = [{1,2;"foo",4.5}]
Debug.Assert v(1, 1) = 1
Debug.Assert v(1, 2) = 2
Debug.Assert v(2, 1) = "foo"
Debug.Assert v(2, 2) = 4.5
'* write all cells in one line
Sheet1.Cells(1, 1).Resize(2, 2).Value2 = v
End Sub
answered Apr 17, 2018 at 22:43
S MeadenS Meaden
8,0313 gold badges31 silver badges65 bronze badges
2
If you don’t need a new instance each time you can use a Static
local variable to avoid multiple objects creation and initialization:
Private Function MyConstants()
Static constants As Variant
If IsEmpty(constants) Then
constants = Array(2, 13, 17)
End If
MyConstants = constants
End Function
answered Jan 30, 2019 at 18:52
PragmateekPragmateek
13.1k9 gold badges73 silver badges108 bronze badges
Can an array be declared as a constant? No.
Workarounds — Simplest one I can think of is to define a constant with delim and then use Split
function to create an array.
Const myConstant = "2,13,17"
Sub Test()
i = Split(myConstant, ",")
For j = LBound(i) To UBound(i)
Debug.Print i(j)
Next
End Sub
answered Dec 8, 2016 at 18:20
Pankaj JajuPankaj Jaju
5,3212 gold badges25 silver badges41 bronze badges
Is this too simplistic?
PUBLIC CONST MyArray = "1,2,3,4"
then later in a module:
Dim Arr as Variant
SET Arr = split(MyArray,",")
answered Mar 3, 2019 at 21:29
1
I know this is an old question, but these archives are often scanned for many years after being posted, so I don’t see a problem with adding things long after the origin date.
How about creating a class, with a read-only property returning the ‘array’ value? You can specify a parameter using the same syntax as an array index, and defining only a GET property effectively makes it read-only. Define the constant values inside the class and it will work just like a constant array, even though the actual construction is different.
answered Mar 21, 2021 at 23:17
Using above information, I came to following working solution for comparing short text information of a month, independent from Excel using German language:
Const MONATE = «,Jän,Feb,März,Apr,Mai,Jun,Jul,Aug,Sep,Okt,Nov,Dez»
.. and later in the code:
If StringToCompare = Split(MONATE, ",")(Month(dt)) Then
NOTE: as the Split-Array starts with index 0 I added the comma in the beginning.
answered Oct 4, 2021 at 18:42
CSohuCSohu
111 bronze badge
Don’t know when this changed, but in Excel 365, this works (or, at least, does not generate a compiler error):
Const table1Defs As Variant = Array("value 1", 42, Range("A1:D20"))
z32a7ul
3,2423 gold badges20 silver badges42 bronze badges
answered Sep 4, 2019 at 16:22
2
dk
MrExcel MVP
-
#2
I’d be very suprised if you could do this. You’d be better off using a variable array, or a custom function which returns the number of days in a given month.
-
#3
I need to revisit this question. There is a need for arrays of constants. I need to add some cells to a worksheet to show average, min, and max. The worksheet is quite asymetrical and the columns to be evaluated are not definable. Here is what I have been able to do as a workaround.
Code:
Dim Evaluation_Array As Variant
Evaluation_Array = Array(3, 4, 5, 6, 8, 11, 15)
For Each Sum_Column_Number In Evaluation_Array
Call Build_Evaluation_Cell(My_Worksheet, _
Sum_Column_Number, _
Sumation_Row, _
Top_Sumation, _
Bottom_Sumation)
Next
The subroutine (in part) adds a summing cell in a row for each of the columns specified. There is more to this, but I hope the code extract above will convey the general concept.
Evaluation_Array really should be an integer, not a variant, as should be Sum_Column_Number. The use of variant requires that the subroutine be declared with a variant rather than an integer.
The original post is approaching five years old now. Can an array of constants be declared?
-
#4
I don’t understand why you would need to do this.
What is the difference between defining this array as a constant, and just defining it by hardcoding the values in to be compiled at run time?
It makes no difference as far as I can see…
You can have the array as an integer, there is no problem there either…. so long as you know the array will be a predetermined length.
e.g.
Code:
option base 1
dim myarray(3) as integer
myarray(1) = 3 : myarray(2) = 4: myarray(3) = 5
Even if you don’t know it would be a pre-determined length, you can use the
keyword to extend the array as and when required.
Am I missing something here?
-
#5
Then again, why do you need the array of days in a month at all? Couldn’t you just use:
Code:
Dim monthnum As Integer
monthnum = 2
MsgBox Day(DateSerial(2006, monthnum + 1, 0))
or similar?
-
#6
Question: Why do we need to be able to declare an array of constants?
First, for the same reason that we need constants, we need an array of constants. And for all of those reasons. I don’t want to build it a run time, I want it predefined at compile time. I have some deadlines and don’t have time to entertain that discussion right now. Get a few books on software engineering and read about software design and constants. Read about writing software for flexibility, robustness and maintainability.
Please bear in mind that example code posted here is often a vehicle used to convey a complex idea. The simplest possible code segment that can convey the question is posed, the often huge amount of complexity behind it is deliberatly omitted. Because the quesion is simple does not mean that the needs are simple.
For now I take it that there is no declaration of constant arrays and will move on. I appreciate the time you took to respond and will leave this thread monitored.
-
#7
It’s not exactly the an array when it’s set as a constant, but the below has similar effects to what you ask:
Code:
Const z As String = "1, 2, 3, 4, 5, 6, 7"
Sub Test()
x = Split(z, ",")
For y = LBound(x) To UBound(x)
MsgBox x(y)
Next
End Sub
-
#8
First, for the same reason that we need constants, we need an array of constants. And for all of those reasons. I don’t want to build it a run time, I want it predefined at compile time. I have some deadlines and don’t have time to entertain that discussion right now. Get a few books on software engineering and read about software design and constants. Read about writing software for flexibility, robustness and maintainability.
I read your response with interest.
First and foremost, this is a discussion forum where people offer help to others for free. I am not being paid to sit here and read your posts, I do it for the love of helping people out.
If you read many of the posts on this forum, as I have, you will notice a trend with posts. That trend is that people often ask questions, under the presumption that the question they pose will help them fix their solution. All to often, however, it emerges that if more detail is given on the actual problem (as opposed to the solution they believe will fix it), other caveats to the problem can be unearthed that lead to the conclusion that the OP’s question can actually be reposed in another form, leading to an answer that satisfies what is the orginal issue.
I stated I did not understand why you would want an array of constants. To this point, I still don’t understand your intentions. If your motivation was made clearer, then as you say, we could cut through this whole portion of analysis and simply offer you solutions that achieve what you want.
I have to take significant issue with your tone. You know nothing about anyones software development history on this board. As it happens I am a graduate in Computer Science from a top UK university. I do not need your patronising advice on getting some ‘books on software design’. I am very aware of software design principles. I work as a software designer here in London, with Java and C++, as well as a little dabbling in VBA. I have answered numerous posts on this forum with no complaints from the OP’s who have got things working as a result. You cannot declare a constant array in VBA. I could have left it there, but decided to try and explore your problem and offer alternative solutions that could act as a workaround for you. Sure constants are only evaluated once as opposed to everytime a variable is used. Yes, there is an overhead to that, but if its important as you say it is, you can use a variable to hold the array, and then use some (now its my time to get patronising) common sense to leave the array alone at run time, and therefore protect its values.
Furthermore, with this high and mighty attitude you seem to have, I would expect you would get little help from the people on this board. This is a community that involves mutual respect, and a culture of helpfulness and learning. Both myself, and Oaktree (a Microsoft most valued professional) have taken the time out of our lives to attempt to address your problem, to try and talk you through your thought process so as to ascertain not only what you want, but why you want it as well. Frankly I find your consequent posts abhorrently patronising and full of negativity.
My advice — change your attitude, and fast, else you’ll find yourself going down in a very negative fashion not only on this medium, but in life in general.
Good day to you.
-
#9
Hi bkelly
1. I agree with you. We should be able to define constant arrays. Whenever the language allows it I define most of the constants at the beginning of the modules, outside the routines.
2 . It is not true what you say: «The use of variant requires that the subroutine be declared with a variant rather than an integer.»
You can (should) use a type conversion function and define the subroutine properly.
Try this:
Code:
Sub ConvType()
Dim v As Variant
v = 2
Call paramtype(CInt(v))
End Sub
Sub paramtype(i As Integer)
MsgBox i & ", " & TypeName(i)
End Sub
3. You can use a workaround like BJungheim’s. This will let you define the constant array at the beginning of the module
Code:
Const sArr As String = "1,3,5,7"
Sub a()
Dim v
For Each v In Split(sArr, ",")
MsgBox CInt(v)
Next
End Sub
4 — It might be better if along with a syntax question you would explain your problem.
There may be other ways of doing what you want that may be more efficient and easier to implement.
In this case, although I don’t have enough information about your problem, I got the feeling that maybe you could use a multiarea range.
If you had explained your problem better, I might be able suggest it or understand that it makes no sense
5. Last but not least:
I have some deadlines and don’t have time to entertain that discussion right now. Get a few books on software engineering and read about software design and constants. Read about writing software for flexibility, robustness and maintainability.
Let me tell you that what you wrote is very unpolite and even a bit aggressive.
As you know we all try to help each other in this board. The attitude from one member towards the others is expected to be polite, even friendly.
An attitude like the one you displayed, if meant, is not welcome.Best regards
PGC
-
#10
Hi pcg,
I just want to point out that it’s Bryan Kelly who is being so rude, and not Hedges.
-
10-30-2004, 05:54 AM
#1
Solved: Declare a Constant Array
Hi,
Can I declare an array in a similar fashion to a constant so that the data can be used by separate elements of a userform and sent to a function for processing. I don’t want to put them on the Userform itself, if I can avoid it.
Something like the following
[VBA] Cols = Array(«A», «D», «G», «H»)Sub Test1()
‘Cols = Array(«A», «D», «G», «H»)
Range(Cols(0) & «3»).Select
End SubSub test2()
Dim Cols()
‘Cols = Array(«A», «D», «G», «H»)
For Each gc In GetCols(Cols)
msg = msg & gc & «, «
Next
MsgBox msg
End SubFunction GetCols(Cols() As Variant) As Variant
Dim MyCols()
ReDim MyCols(UBound(Cols))For i = 0 To UBound(Cols)
MyCols(i) = Range(Cols(i) & «:» & Cols(i)).Column()
Next
GetCols = MyColsEnd Function
[/VBA]
-
10-30-2004, 01:02 PM
#2
Hi MD,
I don’t believe that you can declare a Constant array.
Possible alternatives:
1. A Public array variable that you fill with a ‘starter’ routine.
2. Store the data in a worksheet.
-
10-31-2004, 10:29 PM
#3
How about a public function that returns the array. Function works just like any variables.
Try this.
[vba]
Public Function Arr()
Arr = Array(«a», «b», «c»)
End FunctionSub try()
For Each a In Arr
MsgBox a
Next a
End Sub
[/vba]
-
11-01-2004, 09:57 AM
#4
That’s pretty good Sixth Sense. If that were the method, as I sometimes find myself lacking options, you can add different qualifying lines to your code so you don’t have to keep writing multiple Public Functions. You can just call from the sub routine and assign them in your Function …
[vba]Option Explicit
Public Function Arr(test)
Select Case test
Case «yes»
Arr = Array(«a», «b», «c»)
Case «no»
Arr = Array(«d», «e», «f»)
End Select
End FunctionSub try()
Dim a As Variant, test As String
test = «no»
For Each a In Arr(test)
MsgBox a
Next a
End Sub[/vba]Change the ‘test = «no» ‘ to whatever you wanted, msgbox, returned value, whatever. Just thought I’d throw that out there, fwiw.
-
11-01-2004, 10:40 AM
#5
Hi,
Thanks to all. I’ve decided to use the following, (which works on my test form at least!)
MD
[VBA]
Function Arr(MySet As String)
Select Case MySet
Case Is = «A»
Arr = Array(«A», «B», «C», «D»)
Case Is = «B»
Arr = Array(«E», «F», «G», «H»)
Case Is = «C»
Arr = Array(«I», «J», «K», «L»)
End SelectEnd Function
Private Sub UserForm_Initialize()
For Each A In Arr(«B»)
ListBox1.AddItem A
Next
End Sub
[/VBA]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
- BB code is On
- Smilies are On
- [IMG] code is On
- [VIDEO] code is On
- HTML code is Off
Forum Rules
- Remove From My Forums
-
Question
-
Hi All,
Does it possible to declare const string array like this:
const MY_TABLE(2) AS String=ARRAY(«IN»,»TW»)
-
Edited by
Monday, March 31, 2014 10:14 AM
-
Edited by
Answers
-
Don’t think Array constants are supported by VBA.
Happy to help ! When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answered
-
Proposed as answer by
Michal Krzych
Monday, March 31, 2014 4:22 PM -
Marked as answer by
Luna Zhang — MSFT
Tuesday, April 8, 2014 9:27 AM
-
Proposed as answer by
In this Article
- VBA Array Quick Sheet
- Arrays
- VBA Array Quick Examples
- Array Benefits? – Speed!
- Create / Declare an Array (Dim)
- Static Array
- Dynamic Array
- ReDim vs. ReDim Preserve
- Declaring Arrays Simplified
- Set Array Values
- Get Array Value
- Assign Range to Array
- Output Array to Range
- 2D / Multi-Dimensional Arrays
- Multi-Dimensional Array Examples
- 1D Array Example
- 2D Array Example
- 3D Array Example
- Array Length / Size
- UBound and LBound Functions
- Array Length Function
- Loop Through Array
- For Each Array Loop
- Loop Through 2D Array
- Other Array Tasks
- Clear Array
- Count Array
- Remove Duplicates
- Filter
- IsArray Function
- Join Array
- Split String into Array
- Const Array
- Copy Array
- Transpose
- Function Return Array
- Using Arrays in Access VBA
In VBA, an Array is a single variable that can hold multiple values. Think of an array like a range of cells: each cell can store a value. Arrays can be one-dimensional (think of a single column), two-dimensional (think of multiple rows & columns), or multi-dimensional. Array values can be accessed by their position (index number) within the array.
VBA Array Quick Sheet
Arrays
Create
Dim arr(1 To 3) As Variant
arr(1) = “one”
arr(2) = “two”
arr(3) = “three”
Create From Excel
Dim arr(1 To 3) As Variant
Dim cell As Range, i As Integer
i = LBound(arr)
For Each cell In Range(“A1:A3”)
i = i + 1
arr(i) = cell.value
Next cell
Read All Items
Dim i as Long
For i = LBound(arr) To UBound(arr)
MsgBox arr(i)
Next i
Array to String
Dim sName As String
sName = Join(arr, “:”)
Increase Size
ReDim Preserve arr(0 To 100)
VBA Array Quick Examples
Let’s look at a full example before we dive into specifics:
Sub ArrayExample()
Dim strNames(1 to 4) as String
strNames(1) = "Shelly"
strNames(2) = "Steve"
strNames(3) = "Neema"
strNames(4) = "Jose"
msgbox strNames(3)
End Sub
Here we’ve created the one-dimensional string array: strNames with size four (can hold four values) and assigned the four values. Last we display the 3rd value in a Message Box.
In this case, the benefit of using an Array is small: only one variable declaration is required instead of four.
However, let’s look at an example that will show the true power of an array:
Sub ArrayExample2()
Dim strNames(1 To 60000) As String
Dim i As Long
For i = 1 To 60000
strNames(i) = Cells(i, 1).Value
Next i
End Sub
Here we’ve created an Array that can hold 60,000 values and we’ve quickly populated the array from Column A of a worksheet.
Array Benefits? – Speed!
You might think of Arrays similar to Excel worksheets:
- Each cell (or item in an array) can contain its own value
- Each cell (or item in an array) can be accessed by its row & column position.
- Worksheet Ex. cells(1,4).value = “Row 1, Column 4”
- Array Ex. arrVar(1,4) = “Row 1, Column 4”
So why bother with Arrays? Why not just read and write values directly to cells in Excel? One word: Speed!
Reading / Writing to Excel cells is a slow process. Working with Arrays is much faster!
Create / Declare an Array (Dim)
Note: Arrays can have multiple “dimensions”. To keep things simple, we will start by only working with one-dimensional arrays. Later in the tutorial we will introduce you to multiple-dimension arrays.
Static Array
Static Arrays are arrays that cannot change size. Conversely, Dynamic Arrays can change size. They are declared slightly differently. First, let’s look at static arrays.
Note: If your array won’t change in size, use a static array.
Declaring a static array variable is very similar to declaring a regular variable, except you must define the size of the array. There are several different ways to set the size of an array.
You can explicitly declare the start and end positions of an array:
Sub StaticArray1()
'Creates array with positions 1,2,3,4
Dim arrDemo1(1 To 4) As String
'Creates array with positions 4,5,6,7
Dim arrDemo2(4 To 7) As Long
'Creates array with positions 0,1,2,3
Dim arrDemo3(0 To 3) As Long
End Sub
Or you can enter only the array size:
Sub StaticArray2()
'Creates array with positions 0,1,2,3
Dim arrDemo1(3) As String
End Sub
Important! Notice that by default, Arrays start at position 0. So Dim arrDemo1(3) creates an array with positions 0,1,2,3.
You can declare Option Base 1 at the top of your module so that the array starts at position 1 instead:
Option Base 1
Sub StaticArray3()
'Creates array with positions 1,2,3
Dim arrDemo1(3) As String
End Sub
However, I find that it’s much easier (and less confusing) to just explicitly declare the start and end positions of arrays.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Dynamic Array
Dynamic Arrays are arrays whose size can be changed (or whose size does not need to be defined).
There are two ways to declare a Dynamic Array.
Variant Arrays
The first way to declare a Dynamic Array is by setting the array to type Variant.
Dim arrVar() As Variant
With a Variant Array, you do not need to define the array size. The size will automatically adjust. Just remember that the Array starts with position 0 (unless you add Option Base 1 to the top of your module)
Sub VariantArray()
Dim arrVar() As Variant
'Define Values (Size = 0,1,2,3)
arrVar = Array(1, 2, 3, 4)
'Change Values (Size = 0,1,2,3,4)
arrVar = Array("1a", "2a", "3a", "4a", "5a")
'Output Position 4 ("5a")
MsgBox arrVar(4)
End Sub
Non-Variant Dynamic Arrays
With non-variant arrays, you must define the array size before assigning values to the array. However, the process to create the array is slightly different:
Sub DynamicArray1()
Dim arrDemo1() As String
'Resizes array with positions 1,2,3,4
ReDim arrDemo1(1 To 4)
End Sub
First you declare the array, similar to the static array, except you omit the array size:
Dim arrDemo1() As String
Now when you want to set the array size you use the ReDim command to size the array:
'Resizes array with positions 1,2,3,4
ReDim arrDemo1(1 To 4)
ReDim resizes the array. Read below for the difference between ReDim and ReDim Preserve.
ReDim vs. ReDim Preserve
When you use the ReDim command you clear all existing values from the array. Instead you can use ReDim Preserve to preserve array values:
'Resizes array with positions 1,2,3,4 (Preserving existing values)
ReDim Preserve arrDemo1(1 To 4)
Declaring Arrays Simplified
You might be feeling overwhelmed after reading everything above. To keep things simple, we will mostly work with static arrays for the rest of the article.
VBA Programming | Code Generator does work for you!
Set Array Values
Setting array values is very easy.
With a static array, you must define each position of the array, one at a time:
Sub ArrayExample()
Dim strNames(1 to 4) as String
strNames(1) = "Shelly"
strNames(2) = "Steve"
strNames(3) = "Neema"
strNames(4) = "Jose"
End Sub
With a Variant Array you can define the entire array with one line (only practical for small arrays):
Sub ArrayExample_1Line()
Dim strNames() As Variant
strNames = Array("Shelly", "Steve", "Neema", "Jose")
End Sub
If you attempt to define a value for an array location that does not exist, you will receive a Subscript Out of Range error:
strNames(5) = "Shannon"
In the ‘Assign Range to Array’ section Below we’ll show you how to use a loop to quickly assign large numbers of values to arrays.
Get Array Value
You can fetch array values the same way. In the example below we will write array values to cells:
Range("A1").Value = strNames(1)
Range("A2").Value = strNames(2)
Range("A3").Value = strNames(3)
Range("A4").Value = strNames(4)
Assign Range to Array
To assign a Range to an Array you can use a loop:
Sub RangeToArray()
Dim strNames(1 To 60000) As String
Dim i As Long
For i = 1 To 60000
strNames(i) = Cells(i, 1).Value
Next i
End Sub
This will loop through cells A1:A60000, assigning the cell values to the array.
Output Array to Range
Or you can use a loop to assign an array to a range:
For i = 1 To 60000
Cells(i, 1).Value = strNames(i)
Next i
This will do the reverse: assign array values to cells A1:A60000
2D / Multi-Dimensional Arrays
So far we’ve worked exclusively with single-dimensional (1D) arrays. However, arrays can have up to 32 dimensions.
Think of a 1D array like a single row or column of Excel cells, a 2D array like an entire Excel worksheet with multiple rows and columns, and a 3D array is like an entire workbook, containing multiple sheets each containing multiple rows and columns (You could also think of a 3D array as like a Rubik’s Cube).
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Multi-Dimensional Array Examples
Now let’s demonstrate examples of working with arrays of different dimensions.
1D Array Example
This procedure combines the previous array examples into one procedure, demonstrating how you might use arrays in practice.
Sub ArrayEx_1d()
Dim strNames(1 To 60000) As String
Dim i As Long
'Assign Values to Array
For i = 1 To 60000
strNames(i) = Cells(i, 1).Value
Next i
'Output Array Values to Range
For i = 1 To 60000
Sheets("Output").Cells(i, 1).Value = strNames(i)
Next i
End Sub
2D Array Example
This procedure contains an example of a 2D array:
Sub ArrayEx_2d()
Dim strNames(1 To 60000, 1 To 10) As String
Dim i As Long, j As Long
'Assign Values to Array
For i = 1 To 60000
For j = 1 To 10
strNames(i, j) = Cells(i, j).Value
Next j
Next i
'Output Array Values to Range
For i = 1 To 60000
For j = 1 To 10
Sheets("Output").Cells(i, j).Value = strNames(i, j)
Next j
Next i
End Sub
3D Array Example
This procedure contains an example of a 3D array for working with multiple sheets:
Sub ArrayEx_3d()
Dim strNames(1 To 60000, 1 To 10, 1 To 3) As String
Dim i As Long, j As Long, k As Long
'Assign Values to Array
For k = 1 To 3
For i = 1 To 60000
For j = 1 To 10
strNames(i, j, k) = Sheets("Sheet" & k).Cells(i, j).Value
Next j
Next i
Next k
'Output Array Values to Range
For k = 1 To 3
For i = 1 To 60000
For j = 1 To 10
Sheets("Output" & k).Cells(i, j).Value = strNames(i, j, k)
Next j
Next i
Next k
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Array Length / Size
So far, we’ve introduced you to the different types of arrays and taught you how to declare the arrays and get/set array values. Next we will focus on other necessary topics for working with arrays.
UBound and LBound Functions
The first step to getting the length / size of an array is using the UBound and LBound functions to get the upper and lower bounds of the array:
Sub UBoundLBound()
Dim strNames(1 To 4) As String
MsgBox UBound(strNames)
MsgBox LBound(strNames)
End Sub
Subtracting the two (and adding 1) will give you the length:
GetArrLength = UBound(strNames) - LBound(strNames) + 1
Array Length Function
Here is a function to get a single-dimension array’s length:
Public Function GetArrLength(a As Variant) As Long
If IsEmpty(a) Then
GetArrLength = 0
Else
GetArrLength = UBound(a) - LBound(a) + 1
End If
End Function
Need to calculate the size of a 2D array? Check out our tutorial: Calculate Size of Array.
Loop Through Array
There are two ways to loop through an array. The first loops through the integers corresponding to the number positions of the array. If you know the array size you can specify it directly:
Sub ArrayExample_Loop1()
Dim strNames(1 To 4) As String
Dim i As Long
strNames(1) = "Shelly"
strNames(2) = "Steve"
strNames(3) = "Neema"
strNames(4) = "Jose"
For i = 1 To 4
MsgBox strNames(i)
Next i
End Sub
However, if you don’t know the array size (if the array is dynamic), you can use the LBound and UBound functions from the previous section:
Sub ArrayExample_Loop2()
Dim strNames(1 To 4) As String
Dim i As Long
strNames(1) = "Shelly"
strNames(2) = "Steve"
strNames(3) = "Neema"
strNames(4) = "Jose"
For i = LBound(strNames) To UBound(strNames)
MsgBox strNames(i)
Next i
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
For Each Array Loop
The second method is with a For Each Loop. This loops through each item in the array:
Sub ArrayExample_Loop3()
Dim strNames(1 To 4) As String
Dim Item
strNames(1) = "Shelly"
strNames(2) = "Steve"
strNames(3) = "Neema"
strNames(4) = "Jose"
For Each Item In strNames
MsgBox Item
Next Item
End Sub
The For Each Array Loop will work with multi-dimensional arrays in addition to one-dimensional arrays.
Loop Through 2D Array
You can also use the UBound and LBound functions to loop through a multi-dimensional array as well. In this example we will loop through a 2D array. Notice that the UBound and LBound Functions allow you to specify which dimension of the array to find the upper and lower bounds (1 for first dimension, 2 for second dimension).
Sub ArrayExample_Loop4()
Dim strNames(1 To 4, 1 To 2) As String
Dim i As Long, j As Long
strNames(1, 1) = "Shelly"
strNames(2, 1) = "Steve"
strNames(3, 1) = "Neema"
strNames(4, 1) = "Jose"
strNames(1, 2) = "Shelby"
strNames(2, 2) = "Steven"
strNames(3, 2) = "Nemo"
strNames(4, 2) = "Jesse"
For j = LBound(strNames, 2) To UBound(strNames, 2)
For i = LBound(strNames, 1) To UBound(strNames, 1)
MsgBox strNames(i, j)
Next i
Next j
End Sub
Other Array Tasks
Clear Array
To clear an entire array, use the Erase Statement:
Erase strNames
Usage Example:
Sub ArrayExample()
Dim strNames(1 to 4) as String
strNames(1) = "Shelly"
strNames(2) = "Steve"
strNames(3) = "Neema"
strNames(4) = "Jose"
Erase strNames
End Sub
Alternatively, you can also ReDim the array to resize it, clearing part of the array:
ReDim strNames(1 to 2)
This resizes the array to size 2, deleting positions 3 and 4.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Count Array
You can count the number of positions in each dimension of an array using the UBound and LBound Functions (discussed above).
You can also count the number of entered items (or items that meet certain criteria) by looping through the array.
This example will loop through an array of objects, and count the number of non-blank strings found in the array:
Sub ArrayLoopandCount()
Dim strNames(1 To 4) As String
Dim i As Long, n As Long
strNames(1) = "Shelly"
strNames(2) = "Steve"
For i = LBound(strNames) To UBound(strNames)
If strNames(i) <> "" Then
n = n + 1
End If
Next i
MsgBox n & " non-blank values found."
End Sub
Remove Duplicates
At some point, you may want to remove duplicates from an Array. Unfortunately, VBA does not have a built-in feature to do this. However, we’ve written a function to remove duplicates from an Array (it’s too long to include in this tutorial, but visit the link to learn more).
Filter
The VBA Filter Function allows you to Filter an Array. It does so by creating a new array with only the filtered values. Below is a quick example, but make sure to read the article for more examples for different needs.
Sub Filter_Match()
'Define Array
Dim strNames As Variant
strNames = Array("Steve Smith", "Shannon Smith", "Ryan Johnson")
'Filter Array
Dim strSubNames As Variant
strSubNames = Filter(strNames, "Smith")
'Count Filtered Array
MsgBox "Found " & UBound(strSubNames) - LBound(strSubNames) + 1 & " names."
End Sub
IsArray Function
You can test if a variable is an array using the IsArray Function:
Sub IsArrayEx()
'Creates array with positions 1,2,3
Dim arrDemo1(3) As String
'Creates regular string variable
Dim str As String
MsgBox IsArray(arrDemo1)
MsgBox IsArray(str)
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Join Array
You can quickly “join” an entire array together with the Join Function:
Sub Array_Join()
Dim strNames(1 To 4) As String
Dim joinNames As String
strNames(1) = "Shelly"
strNames(2) = "Steve"
strNames(3) = "Neema"
strNames(4) = "Jose"
joinNames = Join(strNames, ", ")
MsgBox joinNames
End Sub
Split String into Array
The VBA Split Function will split a string of text into an array containing values from the original string. Let’s look at an example:
Sub Array_Split()
Dim Names() As String
Dim joinedNames As String
joinedNames = "Shelly,Steve,Nema,Jose"
Names = Split(joinedNames, ",")
MsgBox Names(1)
End Sub
Here we split this string of text “Shelly,Steve,Nema,Jose” into an array (size 4) using the a comma delimiter (,”).
Const Array
An Array cannot be declared as a constant in VBA. However, you can work around this by creating a function to use as an Array:
' Define ConstantArray
Function ConstantArray()
ConstantArray = Array(4, 12, 21, 100, 5)
End Function
' Retrive ConstantArray Value
Sub RetrieveValues()
MsgBox ConstantArray(3)
End Sub
Copy Array
There is no built-in way to copy an Array using VBA. Instead you will need to use a loop to assign the values from one array to another.
Sub CopyArray()
Dim Arr1(1 To 100) As Long
Dim Arr2(1 To 100) As Long
Dim i As Long
'Create Array1
For i = 1 To 100
Arr1(i) = i
Next i
'CopyArray1 to Array2
For i = 1 To 100
Arr2(i) = Arr1(i)
Next i
MsgBox Arr2(74)
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Transpose
There is no built-in VBA function to allow you to Transpose an array. However, we’ve written a function to Transpose a 2D Array. Read the article to learn more.
Function Return Array
A common question VBA developers have is how to create a function that returns an array. I think most of the difficulties are resolved by using Variant Arrays. We’ve written an article on the topic: VBA Function Return Array.
Using Arrays in Access VBA
Most of the Array examples above work exactly the same in Access VBA as they do in Excel VBA. The one major difference is that when you wish to populate an array using Access data, you would need to loop through the RecordSet object rather than the Range object.
Sub RangeToArrayAccess()
On Error Resume Next
Dim strNames() As String
Dim i As Long
Dim iCount As Long
Dim dbs As Database
Dim rst As Recordset
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("tblClients", dbOpenDynaset)
With rst
.MoveLast
.MoveFirst
iCount = .RecordCount
ReDim strNames(1 To iCount)
For i = 1 To iCount
strNames(i) = rst.Fields("ClientName")
.MoveNext
Next i
End With
rst.Close
Set rst = Nothing
Set dbs = Nothing
End Sub