Search code examples
vbavariant

How to check whether a variant array is unallocated?


   Dim Result() As Variant

In my watch window, this appears as

Expression | Value | Type
Result     |       | Variant/Variant()

How do I check the following:

   if Result is nothing then

or

   if Result is Not Set then

This is basically what I am trying to accomplish, but the first one does not work and the second does not exist.


Solution

  • Chip Pearson made a useful module called modArraySupport that contains a bunch of functions to test for things like this. In your case, you would want to use IsArrayAllocated.

    Public Function IsArrayAllocated(Arr As Variant) As Boolean
    

    This function returns TRUE or FALSE indicating whether the specified array is allocated (not empty). Returns TRUE of the array is a static array or a dynamic that has been allocated with a Redim statement. Returns FALSE if the array is a dynamic array that has not yet been sized with ReDim or that has been deallocated with the Erase statement. This function is basically the opposite of ArrayIsEmpty. For example,

    Dim V() As Variant
    Dim R As Boolean
    R = IsArrayAllocated(V)  ' returns false
    ReDim V(1 To 10)
    R = IsArrayAllocated(V)  ' returns true
    

    The technique used is basically to test the array bounds (as suggested by @Tim Williams) BUT with an extra gotcha.

    To test in your immediate window:

    ?IsArrayAllocated(Result)
    

    Testing in Watch window: there are may ways to do this; for example, add a watch on R and under "Watch Type" select "Break When Value Changes".