I'm trying to create my first user-defined type in VBA and I'm stuck here. 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. 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.
With just a couple of click the Encapsulate Field refactoring changes the code in the OP answer to
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.