The Scope and Lifetime of Variables
If you declare a variable within a procedure, only code within that procedure can access that variable. The scope is local to that procedure. You will often need variables that can be used by several procedures or even the whole application. For these reasons, you can declare a variable at the local, module, or global level.
A local variable uses Dim, Static, or ReDim (arrays only) to declare the variable within a procedure. Several procedures can have a variable called temp, but because every variable is local to its procedure, they all act independently of each other and can hold different values. Local variables declared with the Dim statement remain in existence only as long as the procedure is executing. Local variables declared with Static remain in existence for the lifetime of the application. You may well wish to maintain a variable value throughout the application, and you will see an example of how a static variable can make a difference to your code.
You can also dimension a variable as an array of several elements, and even several dimensions. An array is almost exactly like a spreadsheet in concept. You can define an array with ten elements so it has ten pigeonholes or cells to store information. You can also give it another dimension so it is a 10 by 10 array and has 100 pigeonholes or cells to store your information. An array gives you tremendous flexibility over storing data-it is like poking the data into individual spreadsheet cells. For example, if you recursively searched a disk drive for all subdirectories on it, the way Windows Explorer does, then you would need an array to store all the pathnames as they were found so you could easily find and refer to them within your program.
ReDim Preserve A(12)
To use ReDim, you must define the variable initially as an array (see the section "Arrays" later in this tutorial). Dim A(3) creates a small array with four elements (0-3), so there are effectively four A variables. ReDim A(10) then makes it an 11-element array but loses all the data in it. ReDim A(12) Preserve makes a 13-element array but keeps all existing data. Note all subscripts start at 0 by default.
ReDim is useful when you need an array to store data but you do not know how many elements you will need. For example, if you are recursively searching directories, you have no idea how many will be on a disk device, so you start by specifying a small array of ten elements. As this fills up, it can be resized using ReDim and Preserve to retain the data already in it.