首页 > 解决方案 > Excel VBA:我应该使用类模块吗?

问题描述

Heylo,我一直在努力让我的代码更简洁、更好、更高效。我也一直在寻求使其更易于使用和更易于维护。我有 C/C++ 中面向对象编程的经验,但我一直在避免使用 Excel VBA。我一直在阅读 VBA 中的类模块,但我无法确定它们是否适合我的情况。

我有一个具有普通模块的自定义 Excel 加载项。这个模块(通常称为“Module1”)包含大约 18 个子程序,它们都做完全不同的事情。这些子例程中的每一个都使用每个子例程中的参数连接到自定义选项卡中的自定​​义按钮ByVal control As IRibbonControl,并使用一些功能区 XML 来驱动布局和功能。

无论如何,作为一个例子,如果我要实现它们,我已经写了我认为类模块和普通模块在我的情况下的样子:

' Class Module: TestClass
Private sumVal As Double
Private wsNames As String
Public Sub Add(myRange as Range)
   For Each myCell In myRange
      sumVal = sumVal + myCell.Value
   Next myCell
   MsgBox "The sum of your range is: " & sumVal
End Sub

Public Sub ChangeSettings()
   Application.Calculation = xlCalculationManual
   Application.ScreenUpdating = False
   Application.DisplayStatusBar = False
   MsgBox "The settings have been changed!"
End Sub

Public Sub PrintHello()
   MsgBox "Hellurrr!"
End Sub

Public Sub PrintSheetNames()
   Dim ws As Worksheet
   For Each ws In ActiveWorkbook.Sheets
      wsNames = wsNames + ws.Name + ", "
   Next ws
   MsgBox "The names of all sheets in this workbook are: " & wsNames
End Sub



' Normal Module: Module1
Sub RunAdd(ByVal control As IRibbonControl)
   Dim ClsObj As New TestClass
   Dim theRange As Range
   Set theRange = Selection
   ClsObj.Add theRange
End Sub

Sub RunChangeSettings(ByVal control As IRibbonControl)
   Dim ClsObj As New TestClass
   ClsObj.ChangeSettings
End Sub

Sub RunPrintHello(ByVal control As IRibbonControl)
   Dim ClsObj As New TestClass
   ClsObj.PrintHello
End Sub

Sub RunPrintSheetNames(ByVal control As IRibbonControl)
   Dim ClsObj As New TestClass
   ClsObj.PrintSheetNames
End Sub

像这个例子一样,我拥有的所有子程序本质上都是不同的。我的子程序不共享变量或属性(因此标志性的 Car 类不适用),一个子程序也不执行其他几个子程序。

将我当前的普通模块重新格式化为新的类模块 + 普通模块(作为驱动程序)是否对我的情况有益?

感谢您提前提出的任何意见。

标签: vbaexcelclassmodule

解决方案


根据您提供的代码,使用类模块实际上没有意义。

类模块用于定义自定义对象。

Chip Pearson 的网站在这个主题上有很好的内容:http ://www.cpearson.com/excel/classes.aspx


推荐阅读