【问题标题】:Invalid Use of property vba class属性 vba 类的无效使用
【发布时间】:2019-07-31 17:40:49
【问题描述】:

我在 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

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

Dim stud1 As New Student

stud1.setName "Andy"

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

【问题讨论】:

  • 在接受的答案之上; GetMean() 对我来说似乎无效; marks 在任何地方都没有标注尺寸,除非它是一个错字,因为您在 _ 末尾缺少下划线。每个循环中的迭代器也必须是变体类型 - 你有一个双精度。如果 setter 和 getter 都是公共的,那么拥有公共属性的意义何在?而不是有两个属性只是维度namesurname作为公共变量,VBA会将它们视为一个类'properties
  • 你是正确的我。对于getmean(),这是一个错字。公开name 和 `surname.这仅用于学术目的。

标签: vba excel properties


【解决方案1】:

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

Dim stud1 As New Student

stud1.setName = "Andy"

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

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

Public Property Get Name() As String
    Name = name_
End Property

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

Dim stud1 As New Student
'set name
stud1.Name = "Andy"
'get name
MsgBox stud1.Name

【讨论】:

  • 当然,关于属性名称,您是对的。你帮助我理解了“财产”的概念。谢谢
  • +1 simoco 不错的答案,但请看我上面的评论,我相信你知道 :)
  • @mehow,谢谢!我专注于OP问题的“主要”问题:stud1.setName = "Andy",并没有关注getMean属性,我的错:)但是你指出OP错误很好)
猜你喜欢
  • 2021-10-28
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
  • 2013-12-12
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多