I have the Student class in VBA (Excel) implemented as follows
Option Explicit
Private name_ As String
Private surname_ As String
Private marks_ As New Collection
Public Property Get getMean() As Single
Dim sum As Double
Dim mark As Double
Dim count As Integer
For Each mark In marks_
sum = sum + mark
count = count + 1
Next mark
getMean = sum / count
End Property
Public Property Let setName(name As String)
name_ = name
End Property
Public Property Get getName() As String
getName = name_
End Property
Public Property Let setSurname(surname As String)
surname_ = surname
End Property
Public Property Get getSurname() As String
getSurname = surname_
End Property
Then I have a main sub where I write:
Dim stud1 As New Student
stud1.setName "Andy"
I got a compile error on stud1.setName "Andy"
: Invalid use of property.
I don't understand why. Any Idea, please?
Since it's a property (not method) you should use =
to apply a value:
Dim stud1 As New Student
stud1.setName = "Andy"
BTW, for simplicity, you can use the same name for get
and set
properties:
Public Property Let Name(name As String)
name_ = name
End Property
Public Property Get Name() As String
Name = name_
End Property
and then use them as follows:
Dim stud1 As New Student
'set name
stud1.Name = "Andy"
'get name
MsgBox stud1.Name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With