【问题标题】:Are Excel VBA custom made Class Properties useful?Excel VBA 自定义类属性有用吗?
【发布时间】:2019-11-20 15:18:12
【问题描述】:

我一直在使用 VBA for Excel 来实现简单的 Subs 和 Functions 来自动执行任务。

我熟悉 VBA 中的类模块和属性一词,但到目前为止我的所有代码都只包含简单的模块和用户窗体,我想更深入地研究该语言。

我无法理解属性的重要性,特别是我试图理解这两段代码之间的区别:

代码#1

'Class Module: "clsCustomer1"
Option Explicit

Public fName As String
Public sName As String
Public PhoneNumber As String
Public PIN As String
'Module: "Test1"
Sub test1()
    Dim customer1 As New clsCustomer1

    With customer1
        .fName = "John"
        .sName = "Smith"
        .PhoneNumber = "6512346590"
        .PIN = "55648"

        Debug.Print .fName, .sName, .PhoneNumber, .PIN
    End With
End Sub

代码#2

'Class Module: "clsCustomer2"
Option Explicit
Public Property Get cl_fName(ByVal name As String) As String
    cl_fName = name
End Property

Public Property Get cl_sName(ByVal name As String) As String
    cl_sName = name
End Property

Public Property Get cl_PhoneNumber(ByVal number As String) As String
    cl_PhoneNumber = number
End Property

Public Property Get cl_PIN(ByVal number As String) As String
    cl_PIN = number
End Property
'Module: "Test2"
Sub test2()
    Dim customer2 As New clsCustomer2

    With customer2
        Debug.Print _
                    .cl_fName("John"), _
                    .cl_sName("Smith"), _
                    .cl_PhoneNumber("6512346590"), _
                    .cl_PIN("55648")
    End With
End Sub

在这两种情况下,debug.print 都会给出相同的输出。我什至可以在第二种情况下分配相同的变量来匹配第一种情况。普通模块中的实际代码在这两种情况下几乎相同,如果第二个看起来更混乱的话。

既然可以在 Class 模块中声明变量,为什么还要使用 Properties?

显然,我的示例非常简单,但我在这里找不到合适的属性用例。

【问题讨论】:

  • IMO class2 有错误的方式应该如何使用Get。看看例如here.
  • 为什么要有属性而只是公共变量是因为封装,没有它,每个人都可以更改类,迟早会导致意想不到的行为和问题。看看例如here.

标签: excel vba class properties


【解决方案1】:

我想到了两件事。首先,属性可以设置为ReadOnly(甚至WriteOnly)。这有时会很方便。其次,一些属性比仅仅返回值更复杂。一个经典的例子是fullName,它将返回firstName & " " & lastName。因此,获取(或设置)一个属性可能有一些您希望在每次设置(或读取)值时执行的自定义逻辑。但是,如果这两种方法都不适用于特定情况,那么使用方法 #1 是完全可以的。

【讨论】:

  • 但即便如此,当谈到 fullName 时,我是否无法使用属性或类模块获得相同的结果?
  • 当然。您可以避免一起使用类。但人们普遍认为,它们使代码更有条理,更接近现实生活(“客户”类比一堆子类更能反映客户)
  • 同意,感谢您的意见 :) 我会四处寻找更多信息。
  • 另一个好处是,当你将它们声明为属性时,你可以使用智能感知。
猜你喜欢
  • 1970-01-01
  • 2014-02-27
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
相关资源
最近更新 更多