Events
优质
小牛编辑
128浏览
2023-12-01
当您手动更改单元格或单元格值范围时,可以触发事件驱动编程VBA。 更改事件可能会使事情变得更容易,但您可以非常快速地结束充满格式的页面。 有两种事件。
- 工作表事件
- 工作簿活动
工作表事件
当工作表中发生更改时,将触发工作表事件。 它是通过右键单击工作表选项卡并选择“查看代码”,然后粘贴代码来创建的。
用户可以选择这些工作表中的每一个,并从下拉列表中选择“工作表”以获取所有支持的工作表事件的列表。
以下是可由用户添加的受支持的工作表事件。
Private Sub Worksheet_Activate()
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Private Sub Worksheet_Calculate()
Private Sub Worksheet_Change(ByVal Target As Range)
Private Sub Worksheet_Deactivate()
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
例子 (Example)
我们说,我们只需要在双击之前显示一条消息。
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
MsgBox "Before Double Click"
End Sub
输出 (Output)
双击任何单元格后,将向用户显示消息框,如以下屏幕截图所示。
工作簿活动
当工作簿整体发生更改时,将触发工作簿事件。 我们可以通过选择“ThisWorkbook”并从下拉列表中选择“工作簿”来添加工作簿事件的代码,如以下屏幕截图所示。 立即向用户显示Workbook_open子过程,如以下屏幕截图所示。
以下是可由用户添加的受支持的工作簿事件。
Private Sub Workbook_AddinUninstall()
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Private Sub Workbook_BeforePrint(Cancel As Boolean)
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Private Sub Workbook_Deactivate()
Private Sub Workbook_NewSheet(ByVal Sh As Object)
Private Sub Workbook_Open()
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Private Sub Workbook_WindowActivate(ByVal Wn As Window)
Private Sub Workbook_WindowDeactivate(ByVal Wn As Window)
Private Sub Workbook_WindowResize(ByVal Wn As Window)
例子 (Example)
让我们说,我们只需要向用户显示一条消息,无论何时创建新工作表,都会成功创建新工作表。
Private Sub Workbook_NewSheet(ByVal Sh As Object)
MsgBox "New Sheet Created Successfully"
End Sub
输出 (Output)
创建新的Excel工作表后,将向用户显示一条消息,如以下屏幕截图所示。