我是否必须创建一个 class 来处理应用程序级事件?
Do I have to create a class to handle application-level events?
This article 大约
"Using events with the Application object" 状态:
Before you can use events with the Application object, you must create a class module and declare an object of type Application with events.
在我的 ThisWorkbook
s 模块的工作簿中,我有以下代码
Option Explicit
Private WithEvents App As Excel.Application
Private Sub Workbook_Open()
Set App = Application
End Sub
Private Sub App_SomeEvent()
'This event fires without problems
End Sub
代码没有问题,据我测试。然而上面提到的文章让我想到:
我知道 ThisWorkbook
是一个 class 模块,与 sheet 模块相同,但我真的可以将它们用于此目的吗?
在不创建新的 class 模块时,有什么我必须牢记的吗,或者我 必须 创建一个 class 模块的文章是错误的吗?
让 ThisWorkbook 模块处理 Application 事件是完全可以的。
您需要牢记的是,如果有的话,它是否违反了 single responsibility principle。处理应用程序事件不是工作簿的责任。创建专用 class 来处理特定用途的应用程序事件可能有助于保持体系结构整洁。
但是从功能本身的角度来说,是没有问题的。
This article 大约 "Using events with the Application object" 状态:
Before you can use events with the Application object, you must create a class module and declare an object of type Application with events.
在我的 ThisWorkbook
s 模块的工作簿中,我有以下代码
Option Explicit
Private WithEvents App As Excel.Application
Private Sub Workbook_Open()
Set App = Application
End Sub
Private Sub App_SomeEvent()
'This event fires without problems
End Sub
代码没有问题,据我测试。然而上面提到的文章让我想到:
我知道 ThisWorkbook
是一个 class 模块,与 sheet 模块相同,但我真的可以将它们用于此目的吗?
在不创建新的 class 模块时,有什么我必须牢记的吗,或者我 必须 创建一个 class 模块的文章是错误的吗?
让 ThisWorkbook 模块处理 Application 事件是完全可以的。
您需要牢记的是,如果有的话,它是否违反了 single responsibility principle。处理应用程序事件不是工作簿的责任。创建专用 class 来处理特定用途的应用程序事件可能有助于保持体系结构整洁。
但是从功能本身的角度来说,是没有问题的。