将VBA中的类型设置为空?

tyr*_*rex 20 variables vba object user-defined-types

我已经定义了一个具有自己类型的变量

Dim point As DataPoint

Public Type DataPoint
   list as Collection
   name as String
   number as Integer
End Type
Run Code Online (Sandbox Code Playgroud)

我想point一次删除变量的所有值.如果它是一个类,我会使用Set point = New DataPoint或设置Set point = Nothing,但如果它是一个类型我该怎么办?

GSe*_*erg 27

VB中的函数具有保存结果的隐式变量,默认情况下包含默认类型值,这一点可以使您受益.

public function GetBlankPoint() as DataPoint
end function
Run Code Online (Sandbox Code Playgroud)

用法:

point = GetBlankPoint()
Run Code Online (Sandbox Code Playgroud)


Jea*_*ett 24

标准方法是将每个成员单独重置为其默认值.与对象相比,这是用户定义类型的一个限制.

冒着明显的风险:

With point
    Set .list = Nothing
    .name = ""
    .number = 0
End With
Run Code Online (Sandbox Code Playgroud)

或者,您可以创建一个"空白"变量,并在每次要"清除"它时将其分配给变量.

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
Run Code Online (Sandbox Code Playgroud)


Sid*_*out 7

编辑:该死的!遭到JFC的殴打:D

这是另一种在1行中实现的方法;)

Dim point As DataPoint
Dim emptyPoint As DataPoint

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


Sub Sample()
    '~~> Fill the point
    Debug.Print ">"; point.name
    Debug.Print ">"; point.number
    point.name = "a"
    point.number = 25
    Debug.Print ">>"; point.name
    Debug.Print ">>"; point.number
    '~~> Empty the point
    point = emptyPoint
    Debug.Print ">>>"; point.name
    Debug.Print ">>>"; point.number
End Sub
Run Code Online (Sandbox Code Playgroud)

快照

在此输入图像描述