Welcome to the VanDyke Software Forums

Join the discussion today!


Go Back   VanDyke Software Forums > Scripting

Reply
 
Thread Tools Rate Thread Display Modes
  #1  
Old 02-20-2013, 07:33 PM
AndrewEK AndrewEK is offline
Registered User
 
Join Date: Dec 2010
Posts: 35
How to "ReDim Preserve" a Multi-Dimensional Array?

The VBScript Essentials Guide shows an example of using the 'ReDim Preserve'
command to increase the size of a single dimensional array (page 90). When
I try to do the same with a two dimensional array (i.e. increase the size of
the first dimension), I get "Subscript out of Range" error on the "ReDim
Preserve ..." line. Example script is shown below. Is it possible to dynamically
increase the size of a multi-dimensional array?
________________________________________________________________
#$Language="VBScript"
#$Interface="1.0"

Sub Main()
ReDim myArray(2,2)
' Set first and last values
myArray(0,0) = 1
myArray(2,2) = 1
' Increase size of first dimension
myArraySize = UBound(myArray,1)
ReDim Preserve myArray(myArraySize + 1,2)
' Set last value in new array size
myArray(3,2) = 2
End Sub
Reply With Quote
  #2  
Old 02-20-2013, 09:20 PM
dluther dluther is offline
Registered User
 
Join Date: Feb 2013
Posts: 4
When you use Preserve to 'redim' a multidimensional array you can only resize the last dimension.

Picture this:

Code:
Array(2,4) = 

   (1,2),
   (2,2),
   (3,2),
   (4,2)
(not real code)

In this two-dimensional example, the first subscript is the number of columns, and the last is the number of rows. You can increase the number of rows, but not the number of columns.

Any way you could consider using the second dimension as the number of columns, or create a class with multiple elements and make an array of that:

Code:
Class myObject
  Public Item1
  Public Item2
End Class

Dim myArray(4)

For i = 1 to UBound(myArray)
  Set myArray(i) = New myObject
  myArray(i).Item1 = 1
  myArray(i).Item2 = 2
Next
As long as you aren't trying to add new class elements, you should be good to Redim Preserve the array if you need it.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
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
HTML code is Off

Forum Jump


All times are GMT -6. The time now is 09:09 PM.