You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes a way to elegantly solve the problem.
Just so that we're all on the same page, let's assume you want to do something like the situation described above but you don't have Access available to you to hold the data in a table or you don't want to have to deal with the overhead, or you can't use a sheet in Excel, or you don't know how to use a collection class, and so to start you might create an array to hold a variable number of customer names like this,
but you are a good programmer and/or you have read my Guide to Writing Understandable and Maintainable Code
article and so you would do it more like this.
Dim strCustomerArray() As String
You could then create a second array called something like dblSales to hold the sales figures. Then through some process you would fill both arrays and when you wanted to create some sort of report you would loop through both arrays to get the data. That would work, but there's a better way.
A better way
The two arrays described above are of type String and Double respectively, What many people are not aware of, and the basis of this better way, is that the programmer can create his own type. This is done in the Declarations section (and must be done there) at the top of a UserForm, Form, Sheet, or Code Module. For our purposes we can create our type as follows
Private Type CustomerData ' May be Public in a code module
strCustName As String
dblSales As Double
Your type can contain any number of built-in types and once created it can be used exactly
like any of the built-in types, and so you can do the following in a procedure.
Dim CustData() As CustomerData
To fill the array you could do something like the following where intEntry is a variable you would increment while filling the array. (This article assumes you know how to Redim the array to initialize it and Redim Preserve it to add more entries.)
CustData(intEntry).strCustName = ...
CustData(intEntry).dblSales = ...
Rather than incrementing intEntry you can do it this way
CustData(UBound(CustData)).strCustName = ...
CustData(UBound(CustData)).dblSales = ...
and not have to worry about incrementing a variable. Of course to get the data you would do something like the following.
blah1 = CustData(intEntry).strCustName
blah2 = CustData(intEntry).dblSales
One array versus 2 arrays or 6 or 10, maybe not a big deal, but to me it is more elegant and somewhat more clear as to what is going on.
If you find that this article has been helpful, please click the “thumb’s up” button below. Doing so lets me know what is valuable for EE members and provides direction for future articles. It also provides me with positive feedback in the form of a few points. Thanks!