oop - 何时在 VBA 中使用类?

标签 oop vba class

什么时候适合使用 Visual Basic for Applications (VBA) 中的类?

我假设 accelerated development and reduction of introducing bugs对于大多数支持 OOP 的语言来说,这是一个共同的好处。但是对于VBA,有具体的标准吗?

最佳答案

这取决于谁将开发和维护代码。典型的“高级用户”宏编写者破解小型临时应用程序很可能会因使用类而感到困惑。但对于认真的开发,使用类的原因与其他语言相同。您具有与 VB6 相同的限制 - 没有继承 - 但您可以通过使用接口(interface)来实现多态性。

类的一个很好的用途是表示实体和实体的集合。例如,我经常看到 VBA 代码将 Excel 范围复制到二维数组中,然后使用如下代码操作二维数组:

Total = 0
For i = 0 To NumRows-1
    Total = Total + (OrderArray(i,1) * OrderArray(i,3))
Next i

将范围复制到具有适当命名属性的对象集合中更具可读性,例如:

Total = 0
For Each objOrder in colOrders
    Total = Total + objOrder.Quantity * objOrder.Price
Next i

另一个例子是使用类来实现 RAII 设计模式(google 一下)。例如,我可能需要做的一件事是取消对工作表的保护,进行一些操作,然后再次保护它。使用类可确保即使代码中发生错误,工作表也始终会受到保护:

--- WorksheetProtector class module ---

Private m_objWorksheet As Worksheet
Private m_sPassword As String

Public Sub Unprotect(Worksheet As Worksheet, Password As String)
    ' Nothing to do if we didn't define a password for the worksheet
    If Len(Password) = 0 Then Exit Sub

    ' If the worksheet is already unprotected, nothing to do
    If Not Worksheet.ProtectContents Then Exit Sub

    ' Unprotect the worksheet
    Worksheet.Unprotect Password

    ' Remember the worksheet and password so we can protect again
    Set m_objWorksheet = Worksheet
    m_sPassword = Password
End Sub

Public Sub Protect()
    ' Protects the worksheet with the same password used to unprotect it
    If m_objWorksheet Is Nothing Then Exit Sub
    If Len(m_sPassword) = 0 Then Exit Sub

    ' If the worksheet is already protected, nothing to do
    If m_objWorksheet.ProtectContents Then Exit Sub

    m_objWorksheet.Protect m_sPassword
    Set m_objWorksheet = Nothing
    m_sPassword = ""
End Sub

Private Sub Class_Terminate()
    ' Reprotect the worksheet when this object goes out of scope
    On Error Resume Next
    Protect
End Sub

然后您可以使用它来简化您的代码:

Public Sub DoSomething()
   Dim objWorksheetProtector as WorksheetProtector
   Set objWorksheetProtector = New WorksheetProtector
   objWorksheetProtector.Unprotect myWorksheet, myPassword

   ... manipulate myWorksheet - may raise an error

End Sub 

当此 Sub 退出时,objWorksheetProtector 超出范围,工作表再次受到保护。

关于oop - 何时在 VBA 中使用类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/118863/

相关文章:

c++ - 复制多态对象

excel - 从单元格复制数据并将其添加到 Excel Visual Basic

vba - WorksheetFunction.AverageIf 的运行时错误 '1004'

Java:覆盖子类中的抽象方法

oop - 为什么协议(protocol)的关联类型在 Swift 中不使用泛型类型语法?

java - 为什么java接口(interface)不能包含静态方法实现?

excel - 如何使用 Python 在 VBA 对话框上禁用或自动选择 'OK'(Application.DisplayAlerts = False 不起作用)

python - 在理解中引用类变量时出现名称错误

r - 在 R 中创建新的 S3 类方法

c# - 将类转换为另一个类或将类转换为另一个类