1

Inspired by the answer to this question I created a factory for empty arrays. It usually works, but sometimes it doesn't. The array created with the technique described in that post, after being ReDim-ed and a few values assigned to its elements, appears broken from some points of view and appears correct from other points of view.

For example in my real code I see all the correct values in its elements in the Locals window, I see <Variable uses an Automation type not supported in Visual Basic> on the Watch window, I see the correct values on all the elements on some functions and I see only a few correct values on other functions. For example if F1() creates the array and passes it to F2(), F1 sees all the values, but F2 sees only a few of them, while the others appear to be empty (string in this case).

I was not able to reproduce the same exact same behavior in a small snippet, but I reproduced something similar in the code below. Here the bad behavior is the opposite of what I have described above: it works on the code and it doesn't on the Locals window.

I think that a fix for this problem will also fix the real application.

The output of the Immediate window is correct:

enter image description here

The output of the Watch window fails:

enter image description here

The output of the Locals window is wrong:

enter image description here

Here is the code:

Private Declare Sub GetMem2 Lib "msvbvm60" (src As Any, dest As Any)

Sub Test()
  Dim S() As String, I As Integer
  S = NewArrayString
  ReDim Preserve S(9)
  For I = 0 To 9
    S(I) = String(I + 1, "x")
  Next I
  For I = 0 To 9
    Debug.Print I; S(I)
  Next I
  Stop
End Sub

Function NewArrayString() As String()
  Dim V As Variant, NewTypeCode As Integer
  V = Array()
  NewTypeCode = vbArray Or vbString
  GetMem2 NewTypeCode, V
  NewArrayString = V
End Function
Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235
stenci
  • 8,290
  • 14
  • 64
  • 104
  • The type in the safe array probably remains a variant when `ReDim Preserve S(9)` is called. The issue doesn't occur with `ReDim S(9)`. You could simply use `Split(Empty)` to get an empty array of strings. For the other types I would call `SafeArrayRedim`. – Florent B. Feb 14 '18 at 21:59
  • @Florent B. I tried to use `SafeArrayRedim`, but I couldn't get it to work. Can you share a working example? – stenci Feb 16 '18 at 08:18

0 Answers0