What scope should my data objects have in VBA

302 views Asked by At

I am populating a set of arrays from worksheet data. I then manipulate the data before writing it out to another worksheet (see example below).

If I want to then use the same worksheet data again, how can avoid rewriting the code that populates the arrays from the worksheet?

  • Should I write my code in one long procedure so I don't need to repopulate the arrays?
  • Should I make the arrays global so that they can be reused in several procedures?
  • Should I pass the arrays just to the procedures that need them in a long argument list?
  • Any other options?

Sub ManipulateData()
    Dim people(1 To MAX_DATA_ROW) As String
    Dim projects(1 To MAX_DATA_ROW) As String
    Dim startDates(1 To MAX_DATA_ROW) As Date
    Dim endDates(1 To MAX_DATA_ROW) As Date
    ...
    Loop through worksheet cells to populate arrays
    ...
    Do something with array data

End Sub
1

There are 1 answers

1
Hans Olsson On BEST ANSWER

I'd create a class that would contain the arrays as private variables and then create one public sub called Initialise or similar that loads everything up and then other subs/functions as needed to give you the functionality you need.

That way you don't have to pass the arrays around but they're still not global. The problem with making them global is that it's more risk that some other code somewhere else would change the arrays in some way that your code isn't expecting which can be very hard to find since that might be anywhere in the codebase.

Here's an introduction to classes in Excel VBA.