简体   繁体   English

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

[英]Create a property for a user-defined type in vba

I'm trying to create my first user-defined type in VBA and I'm stuck here.我正在尝试在 VBA 中创建我的第一个用户定义类型,但我被困在这里。 I would like to add a "area" property to my type:我想在我的类型中添加一个“区域”属性:

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

In order to call it like this:为了这样称呼它:

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

I think it's not very correct but I can't find how to achieve it !我认为这不是很正确,但我找不到如何实现它!

Thank you for your comments which help me a lot to understand.谢谢你的评论,这对我理解有很大帮助。 Here is my last update which works fine:这是我的最后一次更新,效果很好:

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

Yes, I could make it in external, but it will be useful for me in the future if I know how to do it like this !是的,我可以在外部制作它,但如果我知道如何做到这一点,它将来对我有用! Thanks !谢谢 !

For the OPs anwser you really need properties for all those public fields.对于 OPs anwser,您确实需要所有这些公共字段的属性。 You may think that this is a lot of boilerplate text for little gain.您可能会认为这是很多样板文本,收效甚微。 but it will allow you to validate the inputs.但它将允许您验证输入。 The tedium of the boilerplate is entirely eliminated by the refactoring offered the the free and fantastic Rubberduck addin for VBA.通过为 VBA 提供免费且出色的 Rubberduck 插件,重构完全消除了样板文件的乏味。

With just a couple of click the Encapsulate Field refactoring changes the code in the OP answer to只需单击几下,封装字段重构就会将 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