Search code examples
vbaobjectvariablesuser-defined-types

Set a type in VBA to nothing?


I have defined a variable with an own type, say

Dim point As DataPoint

Public Type DataPoint
   list as Collection
   name as String
   number as Integer
End Type

and I want to delete all values of the variable point at once. If it was a class, I would just use Set point = New DataPoint, or set Set point = Nothing, but how can I proceed if it's a type?


Solution

  • The standard way is to reset each member to its default value individually. This is one limitation of user-defined types compared to objects.

    At the risk of stating the obvious:

    With point
        Set .list = Nothing
        .name = ""
        .number = 0
    End With
    

    Alternatively, you can create a "blank" variable and assign it to your variable each time you want to "clear" it.

    Dim point As DataPoint
    Dim blank As DataPoint
    
    With point
        Set .list = New Collection
        .list.Add "carrots"
        .name = "joe"
        .number = 12
    End With
    
    point = blank 
    ' point members are now reset to default values