在 vba 中为用户定义类型创建 属性

Create a property for a user-defined type in vba

我正在尝试在 VBA 中创建我的第一个用户定义类型,但我被困在这里。我想在我的类型中添加一个“区域”属性 :

Public Type My_Node
    x As Double
    y As Double
    w As Double
    h As Double
    used As Boolean
    area As Double
    area = w * h
End Type

为了这样称呼它:

Dim node as My_Node
Dim surface as double
surface = node.area

我认为这不是很正确,但我找不到如何实现它!

感谢您的评论,这对我的理解有很大帮助。 这是我的最后一次更新,效果很好:

Public x As Double
Public y As Double
Public w As Double
Public h As Double
Public used As Boolean

Public Property Get Area() As Double
    Area = w * h
End Property

是的,我可以在外部制作它,但如果我知道如何这样做,它将对我将来有用! 谢谢!

对于 OP 答案,您确实需要所有这些 public 字段的属性。您可能认为这是大量的样板文本,收效甚微。但它将允许您验证输入。为 VBA.

提供的免费且出色的 Rubberduck 插件提供的重构完全消除了样板文件的单调乏味。

只需单击几下,封装字段重构就会将 OP 答案中的代码更改为


Private Type TClass1
    X As Double
    Y As Double
    W As Double
    H As Double
    Used As Boolean
    Surface As Double
End Type

Private this As TClass1

Public Property Get X() As Double
    X = this.X
End Property

Public Property Let X(ByVal RHS As Double)
    this.X = RHS
End Property

Public Property Get Y() As Double
    Y = this.Y
End Property

Public Property Let Y(ByVal RHS As Double)
    this.Y = RHS
End Property

Public Property Get W() As Double
    W = this.W
End Property

Public Property Let W(ByVal RHS As Double)
    this.W = RHS
End Property

Public Property Get H() As Double
    H = this.H
End Property

Public Property Let H(ByVal RHS As Double)
    this.H = RHS
End Property

Public Property Get Used() As Boolean
    Used = this.Used
End Property

Public Property Let Used(ByVal RHS As Boolean)
    this.Used = RHS
End Property

Public Property Get Surface() As Double
    Surface = this.Surface
End Property

Public Property Let Surface(ByVal RHS As Double)
    this.Surface = RHS
End Property

Public Property Get Area() As Integer
    Area = W * H
End Property