How to check whether a variant array is unallocated?

后端 未结 5 1054
不知归路
不知归路 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 08:51

    I recommend a slightly different approach because I think using language artifacts like (Not Array) = -1 to check for initialization is difficult to read and causes maintenance headaches.

    If you are needing to check for array allocation, most likely it's because you're trying to make your own "vector" type: an array that grows during runtime to accommodate data as it is being added. VBA makes it fairly easy to implement a vector type, if you take advantage of the type system.

    Type Vector
        VectorData() As Variant
        VectorCount As Long
    End Type
    
    Dim MyData As Vector
    
    Sub AddData(NewData As Variant)
        With MyData
            ' If .VectorData hasn't been allocated yet, allocate it with an
            ' initial size of 16 elements.
            If .VectorCount = 0 Then ReDim .VectorData(1 To 16)
    
            .VectorCount = .VectorCount + 1
    
            ' If there is not enough storage for the new element, double the
            ' storage of the vector.
            If .VectorCount > UBound(.VectorData) Then
                ReDim Preserve .VectorData(1 To UBound(.VectorData) * 2)
            End If
    
            .VectorData(.VectorCount) = NewData
        End With
    End Sub
    
    ' Example of looping through the vector:
    For I = 1 To MyData.VectorCount
        ' Process MyData.VectorData(I)
    Next
    

    Notice how there's no need to check for array allocation in this code, because we can just check the VectorCount variable. If it's 0, we know that nothing has been added to the vector yet and therefore the array is unallocated.

    Not only is this code simple and straightforward, vectors also have all the performance advantages of an array, and the amortized cost for adding elements is actually O(1), which is very efficient. The only tradeoff is that, due to how the storage is doubled every time the vector runs out of space, in the worst case 50% of the vector's storage is wasted.

提交回复
热议问题