Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Invalid Use of property vba class

Writer Matthew Barrera

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?

2

1 Answer

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
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.