无效使用属性vba类

the*_*rug 5 excel vba properties excel-vba

我在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
Run Code Online (Sandbox Code Playgroud)

然后我写了一个主要的子:

Dim stud1 As New Student

stud1.setName "Andy"
Run Code Online (Sandbox Code Playgroud)

我收到了编译错误stud1.setName "Andy":无效的属性使用.我不明白为什么.请问有什么想法吗?

Dmi*_*liv 5

因为它是一个属性(而不是方法),你应该使用它=来应用一个值:

Dim stud1 As New Student

stud1.setName = "Andy"
Run Code Online (Sandbox Code Playgroud)

BTW,为简单起见,您可以使用相同的名称getset属性:

Public Property Let Name(name As String)
    name_ = name
End Property

Public Property Get Name() As String
    Name = name_
End Property
Run Code Online (Sandbox Code Playgroud)

然后按如下方式使用它们:

Dim stud1 As New Student
'set name
stud1.Name = "Andy"
'get name
MsgBox stud1.Name
Run Code Online (Sandbox Code Playgroud)

  • 当然你对属性名称是正确的.你帮我理解了"财产"的概念.谢谢 (2认同)