VBA Array - addressing to it by its name - arrays

this is a general VBA Array issue, it is not for MS Office apps (no tables involved).
I'm looking to find out how to create multiple one-dimension arrays at runtime (maybe even public ones), using data from a .csv file.
I can explain. This is an example of how the csv file would look:
------- CSV FILE ----------------------------
Colors,white,red,blue,green (... and so on)
Animals,cat,dog,wolf,bear (...and so on)
Food,cake,bread,garlic (...and so on)
...and so on, more rows
The opening part is solved,
even the part where each row is assigned to a temporary variable,
and more - the row is split into values and assigned to a temporary array.
So, I have:
tempArray1, containing ("Colors", "white", "red" ...etc)
tempArray2, containing ("Animals", "cat", "dog" ...etc)
...
The goal is to create (or to address to) an (existing) array
NAMED after the first value of each row and then assign the rest of the values from row to that array.
Please do not ask me why am I not using a multi-dimensional array.
I have my reasons.
A similar question related to this case is:
if I already have a one-dimension public array, defined, named and populated - let's say it is Colors() - how can I address to it using the value "Colors"?
Not only to address, but also to erase, redim or change values in it?
When I say "Colors" I mean a string value, not 'hard-coded' Colors() into the sub or function.

With respect to your "a similar question related to this case", you can do the following:
Create a public class module containing your array Colors()
Then, add a "Microsoft Script Control" ActiveX control (possibly to your form), and keep it hidden
Add code (as string) dynamically to your ScriptControl, and execute it. Now, if this code contains (as a string), say " Colors(1)="red" " , then it will actually modify the Colors array in your class-module.
Note: However, there's a catch. Since it is a class module, and not a
normal module, it will only modify the object created inside the
script-control. So, you might have to do all the rest of the coding
too in that script-control (by dynamically adding code to it and
executing it), otherwise, all changes would be lost as the scope of
that object would be limited to that code contained inside the
script-control

Related

Adding a new Entry in a Struct holding a TArray as Member value doesn’t update it’s entries

I am currently working on a Character Customization System where a HUDLayout dynamically create Widgets based on a set of Skins available for the Character Selected. A Skin is represented as a Struct called MaterialInstanceContainer and holds a TArray. Player can mix and match their selection according to the Body Parts they select. In order to achieve the final result, I want to create a TMap<string, MaterialInstanceContainer> so that I can map each BodyParts available for selection with the individual material instance targeting the same BodyPart.
ISSUE: My issue is as follow, when I try to foreach over my collection of Material Instances inside my Container, I do a string comparison and if the output is valid, I can then break my struct to access the Material Instance Array and ADD to it however, at the very end of the process, the length of the array inside Material Container is still at zero.
How can I add a new entry in the array that my Material Container Struct hold?
Thanks!
enter image description here
The issue here is actually pretty straight forward: in Blueprints when you 'Find' a member of Map you are not getting it by-reference, instead you get the copy.
This is exactly what happens at the end of your nested loop: You get a copy, you add item to it, and when another iteration kicks-in the copy gets terminated.
And here on my side it returns exactly the same result as expected:
The fix for that would be easy:
After editing a Copy, you can overwrite the Map member by its copy (via 'Add' node).
But in your case it will be more tricky. You cannot just plug the same BreakStruct/Array node that you just used because it would call whole Find sequence again which creates another copy. Look
If you are confused. This code actually looks like this for Unreal's point of view.
So you have to store the the Struct in local variable first, then perform any operations on it and after everything is done - overwrite the Map member by its locally stored copy. And the result is
Map member gets overwritten every time and everything is as it should be.
Well, almost... For some reason your code is stored in Macro. I think you have to change it to a Function to be able to create local struct variable. But it shouldn't be a problem in this specific case because in your code there is no logic that needs to be done in macro.
Hope, it helps

Array constant in a formula with non-adjacent cell references

I need to add an array of non-adjacent cells to my array formula. I have tried all of the following array constant-like ways and they all give me a "There is a problem with this formula error".
'Chart Data'!{A12:A14,D3:D11}
{'Chart Data'!A12:A14,'Chart Data'!D3:D11}
'Chart Data'!{A12,A13,A14,D3:D11}
{'Chart Data'!A12,'Chart Data'!A13,'Chart Data'!A14,'Chart Data'!D3:D11}
'Chart Data'!{A12,A13,A14,D3,D4,D5,D6,D7,D8,D9,D10,D11}
{'Chart Data'!A12,'Chart Data'!A13,'Chart Data'!A14,'Chart Data'!D3,'Chart Data'!D4,'Chart Data'!D5,'Chart Data'!D6,'Chart Data'!D7,'Chart Data'!D8,'Chart Data'!D9,'Chart Data'!D10,'Chart Data'!D11}
Entire formula (the array constant goes where the {#####} is):
{=SUM(((1-References!M1:M12)*({#####}*(G3:G14+F3:F14-0.11)))+((References!M1:M12)*('Chart Data'!A12:A23*(G3:G14+F3:F14-0.11)))+((H2:H13*X3:X14)+(H3:H14*Y3:Y14)+(I2:I13*(V3:V14-X3:X14))+(I3:I14*(W3:W14-Y3:Y14))))}
I am 100% positive that it is this particular array constant that is causing the problem. I can't move the cells I'm referencing to put them in line. Is it even possible to reference a non-adjacent range in an array formula? If it's possible, what am I doing wrong?
There are several ways to do this. The following is very simple and pretty direct so my favorite.
EITHER choose a cell to build your string for your non-contiguous array in OR create a Named Range to do it. I'll show the first as it seems nicest for being able to use the mouse freely, but in both of them you can actually be creative using about how you build the string that will become your array. The main advantage of creating it in a Named Range is no helper cell lying about anywhere.
So, you create that string and then make it an array. Say you have a non-contiguous array needed using cells A12:A14 and C3:C11. You use joining and TEXTJOIN() like so:
="{"&TEXTJOIN(",",FALSE,B12:B14,C3:C11)&"}"
to create a text string of the values in those cells wrapped with the curly braces ({}) just as if you'd typed it in ("hardcoded it"). It will look like this with the right values in those cells:
{1,2,3,1,2,3,4,5,6,7,8,9}
but is ain't an array yet.
Now the magic in THIS method. Create a Named Range, perhaps called String2Array, and give it a formula of:
=EVALUATE(A1)
(or whatever cell you used for the above formula creating the text string that you want to be an array). Make the reference absolute. ($A$1... which it will do for you, just don't edit it to be relative. If you use this for similar work, but need it relative, that will work fine, but it just isn't what is needed here.)
Now replace your placeholder in the formula with the Named Range's name (perhaps you DID use String2Array). And you're done.
A couple other methods use INDEX() or CHOOSE() and you can force things to be arrays using the functions DOLLARDE() and IMREAL() (I found on a helpsite in a 2014 post) and some others do the same kind of thing. In those days, one had to use {CSE} too, but SPILL takes care of that now (with those two weird-seeming friendlies and at least two others). The poster was someone I've seen on this site, EXCELXOR was the name for the site, XOR LX was the name of the member here though the functions were mentioned in a comment by a Lori. Since he covers, it seems, aspects not usually covered in helpsites, looking up some of his work here, or elsewhere too, might be worthwhile to some folks.
But this method is very direct and therefore easy to maintain. And personally, I love the idea that EVALUATE() (must be used IN the Named Range functionality, not cell-side) is the gift that keeps on giving, one wonderfully helpful thing after another.
So many ways. You could even literally build the array in a helper column/row somewhere and reference THAT instead of the non-contiguous addresses. I like the joining+TEXTJOIN() approach best because I can use the mouse to easily get all the blocks into the formula since it is a LIVE formula. But you can type out a string fairly easily too and add the {}'s. Or perhaps a user would type a string of addresses and you'd add them like the formula does above. And you can insert actual values (constants) into the string you are building as well if that is appropriate. And you could build it formulaicly... I wouldn't pick that workload first thing off the pile of choices, but if you were going to do it anyway already, then... or if it's a small build.

How to find out length of an array in VBA? Ubound does not give actual length.

I basically want to write logic such that if certain element is already present in array i dont want to again put it into it. My array is one dimensional. I am not able to understand how filter function works. Please help. Thanks.
I'm not sure I exactly get what you are trying to do.
But what I understand makes me recommend you to use Dictionary (it is basically a Hashmap)
It works with keys and values.
Each element of this Dictionary contains a unique key (a String that is used to access specifically the data you want) and a value attached to it (can be a String, a Number...)
Here is how to use it :
in your VBA page, go to Tools -> References -> add "Microsoft Scripting Runtime" from the list of available references.
Then in your code :
Dim myDico as Dictionary
set myDico = new Dictionary
myDico.add "myKey", 5
msgbox myDico.Item("myKey") '5

Make variable name using loop and string in PowerBuilder

I am interested if it is possible to make variable name in PowerBuilder using a loop and a string. For example:
long ll_go
string lst_new
for ll_go = 1 to 8
lst_new = "text" + ll_go
lst_new.tag = 5500
next
So, it should give me variables text1, text2..,.,text8 and I would be able to assign values for them. Let me know if anybody succeeded, thanks in advance
Your description is lacking some term precision.
If you actually want to dynamically create new variables as "variable in a powerscript subroutine or function" this is simply not possible.
If instead you want to create dynamically some new controls statictext or textedit objects in a window or visual userobject this is possible:
use a local variable of the type of the new object you need to create, e.g. static text
make it a live object (instantiate) with create
set the object properties to whatever you need
"attach" the new object to its parent (either a window or a visual userobject - though any graphicobject is possible with using the win32api SetParent function) with the OpenUserObject() method. Note that you cannot simply add it directly to the parent's Control[] array.
you can also keep the object in your own array for later convenience access to the created objects instead of looping on the Control[] array
once the object is attached it its parent, you can reuse the local variable to create another one
Here is an example:
//put this in a button clicked() event on a window
//i_myedits is declared in instances variables as
//SingleLineEdit i_myedits[]
SingleLineEdit sle
int i
for i = 1 to 8
sle = create singlelineedit
sle.text = string(i)
sle.tag = "text_" + string(i)
sle.height = pixelstounits(20, ypixelstounits!)
sle.width = pixelstounits(100, xpixelstounits!)
parent.openuserobject(sle, pixelstounits(10, xpixelstounits!), pixelstounits(22 * i, ypixelstounits!))
i_myedits[i] = sle //keep our own reference
next
An exemple of values access:
//put that in another button clicked() event
SingleLineEdit sle
int i
string s_msg
for i = 1 to upperbound(i_myedits[])
sle = i_myedits[i]
if i > 1 then s_msg += "~r~n"
s_msg += "edit #" + string(i) + " (" + sle.tag + ") says '" + sle.text + "'"
next
messagebox("Edits values", s_msg)
As you can see, one practicality problem is that you cannot refer to these controls by constructing the control's name like "text"+2, instead you must access the my edits[] array or loop through the controls and test their .tag property if you set it to something specific.
I do not think that it is possible. Workaround could be an array maybe.
Br. Gábor
I'd see two ways to do this, but they aren't as easy as it seems that you were hoping:
1. Control Array
First method would be to go through the control arrays (on windows, tabs and user objects). I'd create a function that took the control name as a string, then another that overloaded the same function and took control name and an array of windowobject. The string-only method would just call the string/array method, passing the string through and adding the window.Control as the second parameter. The string/array method would go through the array, and for each element, get the ClassDefinition. Pull the name off of it, and parse it apart the way you want it to match the string parameter (e.g. for w_test`tab_first`tabpage_first`cb_here, do you want cb_here to match, or tab_first`tabpage_first`cb_here?). Deal with matches as appropriate. When you find a control of type tab or user object, call the string/array function again with the Control array from that object; deal with success/fail returns as appropriate.
2. DataWindow
What you're describing works extremely well with DataWindows, and their Describe() and Modify() functions. Since you pass these functions only a string, you can build not only the control names, but the values they're set to as you would build any string. In fact, you can build multiple Modify() strings together (delimited by a space) and make a single call to Modify(); this is not only faster, but reduces window flicker and visible activity.
Don't fall into the trap of thinking that, since your data isn't from a database, you can't use a DataWindow. Create an external DataWindow, and simply use it with one row inserted during the Constructor event.
As you might guess, I'd strongly favour the DataWindow approach. Not only is it going to perform better, but it's going to provide a lot more flexibility when you want to move on and tag more control types than just static text. (You'll have to do some type casting even with one control type, but if you want to get into multiples, you'll need to start a CHOOSE CASE to handle all your types.)
Good luck,
Terry
You can't create a variable name in a script because the variables have to be declared before you can use them. With PBNI it's possible to generate a name the way you describe and then get a reference to a variable of that name that already exists but I don't think that's what you want. If you want to keep track of additional properties for your controls, just inherit a new user object from whatever it is (sle, mle, etc.) and add the properties you want. Then you can place your user object on a window and use the properties. Another approach is to use the control's Tag property. It holds a string that you can put whatever you want in. PFC uses this technique. Terry's DataWindow solution is a good approach for storing arbitrary data.
Yes, and there are more than one way to skin a cat.
Sounds like you have several properties so I'd use an array of custom non visual user objects, or an array of structures. Otherwise you could probably use something from the .NET framework like a dictionary object or something like that, or a datawidnow using an external datasource, where you can refer to column names as col + ll_index.ToString().
SIMPLE Example:
Make custom NVO with following instance variables, plus getter/setter functions for each, name it n_single_field
// add the properties and recommend getter and setter functions
public string myTag
public string myText
public int myTabOrder
...
// To USE the NVO define an unbounded array
n_single_field fields[]
// to process the populated fields
integer li_x, li_max_fields
// loop through field 1 through max using array index for field number
li_max_fields = upperbound(fields)
for li_x = 1 to li_max_fields
fields[li_x].myTag = 'abc'
fields[li_x].myText = 'text for field number ' + li_x.ToString()
fields[li_x].myTabOrder = li_x * 10
next
Maybe I'm oversimplifying if so let me know, if there is a will there is always a way. ;)

Excel VBA Programming with Arrays: To Pass them or Not To Pass them?

Question: I am wondering which is the optimal solution for dealing with Arrays in Excel 2003 VBA
Background: I have a Macro in Excel 2003 that is over 5000 lines. I have built it over the last 2 years adding new features as new Procedures, which helps to segment the code and debug, change, or add to that feature. The downside is that I am using much of the same base information in multiple procedures, which requires me to load it into arrays with minor differences multiple times. I am now running into issues with the length of run time, so I am now able to do a full rewrite.
This file is used to grab multiple items of manufacturing flows (up to 4 different set ups with a total of up to 10 distinct flows , of up to 1000 steps each) with the information being Flow specific, Sub-Flow specific for grouping / sorting purposes, and Data (such as movements, inventory, CT, ...)
It then will stick the data onto multiple sheets used to manage the process utilizing data sheets to be perused, charts, and Cell Formatting to denote process flow capability / history.
The Flow is in the Excel File, while the Manufacturing data is read in with 7 different OO4O Oracle SQL pulls, some reused multiple times
The Arrays are:
arrrFlow(1 to 1000, 1 to 4) as a Record Type with 4 strings
arrrSubFlow(1 to 1000, 1 to 10) as a Record Type with 4 strings, 2 integers, and 1 single
arrrData(1 to 1000, 1 to 10) as a Record Type with 1 string, 4 integers, 12 longs, and 1 single
arriSort(1 to 1000, 1 to 4) as Integer (Used as a pointer Array to sort the Flow, Sub Flow, and Data in a Group, Sub Group, and Step order while leaving the original arrays in Step order)
Possibilities:
1) Rewrite the macro into one big procedure that loads the data into master arrays dimensioned within the Procedure once
Pro: Dimensioned in the Procedure rather than as a Public Variable in the Module and not passed.
Con: Harder to debug with one mega procedure instead of multiple smaller ones.
2) Keep macro with multiple procedures but passing the Arrays
Pro: Easier to debug code with multiple smaller procedures.
Con: Passing Arrays (Expensive?)
3) Keep macro with multiple procedures but with the Arrays being Public Dim'ed variables in the Module
Pro: Easier to debug code with multiple smaller procedures.
Con: Public Arrays (Expensive?)
So, what's the community's verdict? Does anyone know the expense of using Public Arrays vs Passing Arrays? Is the Cost of either of these worth losing the ease of having my procedures being focused on one feature?
UPDATE:
I load Inventory Data at a discrete level (multiple per Step), Moves Data at a aggregate level (one per step), and the Beginning of Shift Inventory at an aggregate level. I aggregate the Inventory data by step placing it in Work State categories (Run, Wait,...) I create targets off data already on the sheets.
I have a Flow sheet that shows the Work Flows by Type, currently 3 products have a similar but not exactly the same flow, and 2 products are a different flow, that are similar but again not the same as each other. I have assigned each set of steps in the different flows a group and sub-group.
I place this data on multiple sheets, some in Step Order, some in group / sub-group order. I also need the data summed up by group and product, group / sub-group and product, portion of the line and product, and product.
I use Record Types so I actually have a readable three dimensional array, arrSubFlow(1,1).strStep (Step Name of the 1st Step of the 1st Device), arrData(10,5).lngYest (Yesterday's movement for the 10th Step of the 5th Device).
My main point of optimization is going to be in the section where I create 10 pages from scratch every single time. With Merging Cells, Borders, Headers, ... This is a very time consuming process. I will add a section that will compare my data with the page to see if it needs to be changed and if so, only then recreate it otherwise, I'll clear each section of data and only write data that changes to the sheet. This will be huge, based on my time logging data. However, whenever I update code, I always try to improve other aspects of the code as well. I see the loading of the data into a Structure (Array, RecordSet, Collection) once as both a little bit of optimization, but more so for data integrity, so I do not have the opportunity to load it differently for different sheets.
The main issues I see getting away from Arrays right now are:
* Already heavily invested in them, but this is not a good enough reason to not change
* Don't know if there is much cost to passing them, since it will by ByRef
* I use a Sort Function to create a Sorted "Pointer" array that lets me leave the Array in Step Flow order, while easily referencing it by Group / Sub-group order.
Since I am always trying to make my code for now and the future, I am not against updating the arrays to either RecordSets or Collections, but not merely for the sake of changing them to learn something cool. My arrays work and from my research, they add seconds to the run time, not substantial amounts for this 2 minute report. So If another structure is easier to update in the future than Two-dimensional Arrays of Record Types, then please let me know, but does anyone know the cost of passing an Array to a procedure, assuming you are not doing a ByVal pass?
You've provided a good bit of detail, but it's still quite difficult to understand exactly what's going on without seeing some code. In your question, I can identify at least 4 big topics that you interweave throughout: Manufacturing, Data Access, VBA, and Coding Best-Practices. It's hard for me to tell exactly what you're asking because your question scope is huge. Either way, I appreciate your trying to write better code in VBA.
It's hard for me to understand exactly what you plan to do with the arrays. You say:
The downside is that I am using much of the same base information in multiple procedures, which requires me to load it into arrays with minor differences multiple times.
I'm not sure what you mean here. Are you using arrays to represent a row of data that you retrieved from a database? If so, you might consider using class modules instead of the usual "macro" modules. These will allow you to work with full-blown objects instead of arrays of values (or references, as the case may be). Classes take more work to set up and consume, but they make your code a lot easier to work with and will greatly help you to segment your code.
As user Emtucifor already pointed out, there may be objects such as ADO Recordset objects (which may require Access to be installed...not sure) that can help greatly. Or you might create your own.
Here's a long example of how using a class might help you. Although this example is lengthy, it will show you how a few principles of object-oriented programming can really help you clean up your code.
In the VBA editor, go to Insert > Class Module. In the Properties window (bottom left of the screen by default), change the name of the module to WorkLogItem. Add the following code to the class:
Option Explicit
Private pTaskID As Long
Private pPersonName As String
Private pHoursWorked As Double
Public Property Get TaskID() As Long
TaskID = pTaskID
End Property
Public Property Let TaskID(lTaskID As Long)
pTaskID = lTaskID
End Property
Public Property Get PersonName() As String
PersonName = pPersonName
End Property
Public Property Let PersonName(lPersonName As String)
pPersonName = lPersonName
End Property
Public Property Get HoursWorked() As Double
HoursWorked = pHoursWorked
End Property
Public Property Let HoursWorked(lHoursWorked As Double)
pHoursWorked = lHoursWorked
End Property
The above code will give us a strongly-typed object that's specific to the data with which we're working. When you use multi-dimension arrays to store your data, your code resembles this: arr(1,1) is the ID, arr(1,2) is the PersonName, and arr(1,3) is the HoursWorked. Using that syntax, it's hard to know what is what. Let's assume you still load your objects into an array, but instead use the WorkLogItem that we created above. This name, you would be able to do arr(1).PersonName to get the person's name. That makes your code much easier to read.
Let's keep moving with this example. Instead of storing the objects in array, we'll try using a collection.
Next, add a new class module and call it ProcessWorkLog. Put the following code in there:
Option Explicit
Private pWorkLogItems As Collection
Public Property Get WorkLogItems() As Collection
Set WorkLogItems = pWorkLogItems
End Property
Public Property Set WorkLogItems(lWorkLogItem As Collection)
Set pWorkLogItems = lWorkLogItem
End Property
Function GetHoursWorked(strPersonName As String) As Double
On Error GoTo Handle_Errors
Dim wli As WorkLogItem
Dim doubleTotal As Double
doubleTotal = 0
For Each wli In WorkLogItems
If strPersonName = wli.PersonName Then
doubleTotal = doubleTotal + wli.HoursWorked
End If
Next wli
Exit_Here:
GetHoursWorked = doubleTotal
Exit Function
Handle_Errors:
'You will probably want to catch the error that will '
'occur if WorkLogItems has not been set '
Resume Exit_Here
End Function
The above class is going to be used to "do something" with a colleciton of WorkLogItem. Initially, we just set it up to count the total number of hours worked. Let's test the code we wrote. Create a new Module (not a class module this time; just a "regular" module). Paste the following code in the module:
Option Explicit
Function PopulateArray() As Collection
Dim clnWlis As Collection
Dim wli As WorkLogItem
'Put some data in the collection'
Set clnWlis = New Collection
Set wli = New WorkLogItem
wli.TaskID = 1
wli.PersonName = "Fred"
wli.HoursWorked = 4.5
clnWlis.Add wli
Set wli = New WorkLogItem
wli.TaskID = 2
wli.PersonName = "Sally"
wli.HoursWorked = 3
clnWlis.Add wli
Set wli = New WorkLogItem
wli.TaskID = 3
wli.PersonName = "Fred"
wli.HoursWorked = 2.5
clnWlis.Add wli
Set PopulateArray = clnWlis
End Function
Sub TestGetHoursWorked()
Dim pwl As ProcessWorkLog
Dim arrWli() As WorkLogItem
Set pwl = New ProcessWorkLog
Set pwl.WorkLogItems = PopulateArray()
Debug.Print pwl.GetHoursWorked("Fred")
End Sub
In the above code, PopulateArray() simply creates a collection of WorkLogItem. In your real code, you might create class to parse your Excel sheets or your data objects to fill a collection or an array.
The TestGetHoursWorked() code simply demonstrates how the classes were used. You notice that ProcessWorkLog is instantiated as an object. After it is instantiated, a collection of WorkLogItem becomes part of the pwl object. You notice this in the line Set pwl.WorkLogItems = PopulateArray(). Next, we simply call the function we wrote which acts upon the collection WorkLogItems.
Why is this helpful?
Let's suppose your data changes and you want to add a new method. Suppose your WorkLogItem now includes a field for HoursOnBreak and you want to add a new method to calculate that.
All you need to do is add a property to WorkLogItem like so:
Private pHoursOnBreak As Double
Public Property Get HoursOnBreak() As Double
HoursOnBreak = pHoursOnBreak
End Property
Public Property Let HoursOnBreak(lHoursOnBreak As Double)
pHoursOnBreak = lHoursOnBreak
End Property
Of course, you'll need to change your method for populating your collection (the sample method I used was PopulateArray(), but you probably should have a separate class just for this). Then you just add your new method to your ProcessWorkLog class:
Function GetHoursOnBreak(strPersonName As String) As Double
'Code to get hours on break
End Function
Now, if we wanted to update our TestGetHoursWorked() method to return result of GetHoursOnBreak, all we would have to do as add the following line:
Debug.Print pwl.GetHoursOnBreak("Fred")
If you passed in an array of values that represented your data, you would have to find every place in your code where you used the arrays and then update it accordingly. If you use classes (and their instantiated objects) instead, you can much more easily update your code to work with changes. Also, when you allow the class to be consumed in multiple ways (perhaps one function needs only 4 of the objects properties while another function will need 6), they can still reference the same object. This keeps you from having multiple arrays for different types of functions.
For further reading, I would highly recommend getting a copy of VBA Developer's Handbook, 2nd edition. The book is full of great examples and best practices and tons of sample code. If you're investing a lot of time into VBA for a serious project, it's well worth your time to look into this book.
It sounds like maybe Excel and arrays are not the best tools for the job you're doing. If you could please explain a little bit about the type of data that you're working with and what you're doing, that will really help provide a better answer. Give as much detail as you can about the types of manipulations you're doing on the data and what the inputs and outputs are.
I'm going to give some highlights that I think will help you, and then may edit my answer to be more complete as I get responses from you, and so I have more time to flesh things out a bit.
There is an object that naturally handles the record-type objects you're working with called a Recordset. In the VBA editor, go to Tools -> References and add Microsoft ActiveX Data Objects 2.X Library (the highest one on your machine). You can declare an object of type ADODB.Recordset, then do Recordset.Fields.Append to add fields to it, then .Open it and finally .AddNew, set field values, and .Update. This is a natural object to pass around in programs as an input or output parameter. It has natural traversal and positioning functions (.Eof, .Bof, .AbsolutePosition, .MoveNext, .MoveFirst, .MovePrevious) and supports searching and filtering (.Filter = "Field = 'abc'", .Find and so on).
I don't recommend using public variables, though without an understanding of what you're doing I can't really advise you well here.
I also would avoid one big procedure. Code should be broken out into reusable functional units that do only one thing, whose names are essentially self-documenting about what they do.
If you want to improve the performance of your code, hit ctrl-break at random times while it's running and break into the code. Then press Ctrl-L to view the call stack. Make a note of what is in the list each time. If any item shows up a majority of the time, it is the bottleneck and is where you should spend your time trying to optimize it. However, I don't advise trying to optimize what you have until you make some higher-level decisions (like whether you will switch to a recordset).
I really need more information to help you better.
If you're interested, I'll work up some demonstration code that will show how useful the Recordset object is. Inserting the data from a Recordset into an Excel range is super easy with Recordset.GetRows or .GetString (though some array transposition may be required, that's not hard, either).
UPDATE: If your goal is to speed up your process, then before doing anything I think it's best to be armed with the knowledge of what is taking the most time. Would you please hit ctrl-break about 10 times and note down the call stack each time, then tell me what the most common items in the call stack are?
In terms of updating the speed of cell formatting, here's my experience:
Merge is the slowest operation you can possibly do. Try to avoid it if at all possible. Using "center across selection" is one alternative. Another is just not merging, but using some combination of sizing properly, borders, cell background color, and turning off gridlines for the entire workbook.
Apply borders or other formatting once to the largest thing possible instead of to many small things such as cell by cell. For example, if most cells have all borders but some don't, then apply all borders to the entire range and during your looping remove the ones you don't want. And even then, try to do entire rows and larger ranges.
Save a template file with borders and formatting already applied. Let's say you put one row in it with the formatting for a certain section. In one step duplicate that row into as many rows are needed for that section, say 20 rows, and they will all have the same formatting. Duplicating rows is MUCH faster than applying formatting cell by cell.
Also, I wouldn't automatically go for using classes. While OO is great and I do it myself (heck, I just built 8 classes for something the other day to model a hierarchical structure so I could easily expose the parts of it when I needed them), in practice it can be slower. A simple set of public variables in a class is faster than using getters and setters. A user defined Type is even faster than a class, but you can run into gotchas trying to pass around UDTs in classes (they have to be declared in a non-class public module and even then they can give problems).

Resources