属性 vba 类的无效使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21502969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:40:59  来源:igfitidea点击:

Invalid Use of property vba class

vbaexcel-vbapropertiesexcel

提问by the_drug

I have the Student class in VBA (Excel) implemented as follows

我在 VBA (Excel) 中实现了 Student 类,如下所示

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?

我在以下方面遇到编译错误stud1.setName "Andy":无效使用属性。我不明白为什么。有什么想法吗?

回答by Dmitry Pavliv

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 getand setproperties:

顺便说一句,为简单起见,您可以对getset属性使用相同的名称:

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