View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
joeu2004 joeu2004 is offline
external usenet poster
 
Posts: 2,059
Default 2D array of strings problem

On Feb 18, 10:18*pm, "Robert Crandal" wrote:
Sub DoStuff (A as Integer, B as Integer)
Dim (A, B) as String * ' This creates an error!
End Sub

[....]
Is it possible to create a 2D array whose size depends
on the values of A and B above?


Yes: use ReDim instead Dim. For example:

Sub doit1(a As Long, b As Long)
ReDim s(a, b) As String
MsgBox "a=" & a & " b=" & b & Chr(10) & _
LBound(s, 1) & ":" & UBound(s, 1) & _
" " & LBound(s, 2) & ":" & UBound(s, 2)
End Sub

Sub callit1()
doit1 12, 34
doit1 23, 45
End Sub

However, in that form, the lower bound depends on the Option Base. It
would be prudent to specify it explicitly, for example:

ReDim s(1 to a, 1 to b) As String


The size of this 2D array will stay constant for the duration
of the "DoStuff" procedure, so I only need to set it's size once.


So place the ReDim statement early in the procedure.

However, if you mean that you want to set the size only on the first
call and retain the original size on subsequent calls even if a and b
are different, you could do the following:

Sub doit2(a As Long, b As Long)
Static first As Long
Static s 'must be Variant type
If first = 0 Then
'first call only
first = 1: ReDim s(a, b) As String
s(1, 1) = "s(1,1)": s(1, 2) = "s(1,2)"
s(2, 1) = "s(2,1)": s(2, 2) = "s(2,2)"
End If
MsgBox "a=" & a & " b=" & b & Chr(10) & _
LBound(s, 1) & ":" & UBound(s, 1) & _
" " & LBound(s, 2) & ":" & UBound(s, 2) & _
Chr(10) & _
":" & s(1, 1) & ":" & s(1, 2) & ":" & _
s(2, 1) & ":" & s(2, 2) & ":"
End Sub

Sub callit2()
doit2 12, 34
doit2 23, 45
End Sub