繁体   English   中英

为 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

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

对于 OPs anwser,您确实需要所有这些公共字段的属性。 您可能会认为这是很多样板文本,收效甚微。 但它将允许您验证输入。 通过为 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM