[英]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.