tags:

views:

252

answers:

3

Given the following statements in VBA:
Assume that val = 4 and Option Base 0

Dim dataStr() As String
ReDim dataStr(val)

Will the ReDim statement intialise the String array dataStr to 5 empty string elements(0 to 4).
What exactly will be the contents of the Array after the execution of the ReDim statement.

+1  A: 
Sub RedimStringArray()

Dim Val As Integer
Dim dataStr() As String
Dim idx As Long

    Val = 4

    ReDim dataStr(Val)

    For idx = LBound(dataStr) To UBound(dataStr)
        Debug.Print idx, """" & dataStr(idx); """", TypeName(dataStr(idx)), Len(dataStr(idx))
    Next

End Sub

gives me this:

 0            ""            String         0 
 1            ""            String         0 
 2            ""            String         0 
 3            ""            String         0 
 4            ""            String         0

So I'd say that yes, ReDim re-initializes the array with empty strings.

Mike Woodhouse
Why did you "Dim idx As Long", why not "Dim idx As Integer"
Kevin Boyd
At least in Excel on Win32, Long is the "native" VBA integer type; Integer just gets converted to Long. So, it's common to see integral variables declared as Long by default. Declaring a variable as Integer means you actually want VBA to treat it like one, raising an overflow error if you assign it 32768, etc.
jtolle
+1  A: 

Just to confirm the answer from Mike Woodhouse, see section 5.4.3.3 of the VBA Language Specification:

http://msdn.microsoft.com/en-us/library/dd361851%28PROT.10%29.aspx

Each array in a <redim-statement> is resized according to the dimensions specified in its <bounds-list>. Each element in the array is reset to the default value for its data type, unless the word “preserve” is specified.

jtolle
+2  A: 

You could just read the VB6 manual page on ReDim?

When variables are initialized, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros

MarkJ
"a fixed-length string is filled with zeros" sounds odd. I guess by "zero" they mean Chr$(0).
onedaywhen
...good point about fixed-length strings arrays not being initalized as zero-lenth strings, though.
onedaywhen
Yes, it's Chr$(0). It sounds to me like the VB6 runtime fills the whole block of memory for the array with zeros. So numbers go to zero, pointers go to null, but fixed-length strings go to Chr$(0).
MarkJ