How to check whether a variant array is unallocated?

后端 未结 5 1056
不知归路
不知归路 2020-12-15 08:16
   Dim Result() As Variant

In my watch window, this appears as

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


        
5条回答
  •  清歌不尽
    2020-12-15 09:07

    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".

提交回复
热议问题