VBA - 事件

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)

示例

比方说,我们只需要在双击之前显示一条消息。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
   MsgBox "Before Double Click"
End Sub

输出

双击任何单元格时,将向用户显示消息框,如以下屏幕截图所示。

输入框演示

工作簿事件

当工作簿整体发生更改时,会触发工作簿事件。 我们可以通过选择"ThisWorkbook"并从下拉列表中选择"workbook"来添加工作簿事件的代码,如以下屏幕截图所示。 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)

示例

假设,每当创建新工作表时,我们只需要向用户显示一条消息,表明新工作表已成功创建。

Private Sub Workbook_NewSheet(ByVal Sh As Object)
   MsgBox "New Sheet Created Successfully"
End Sub

输出

创建新的 Excel 工作表后,会向用户显示一条消息,如以下屏幕截图所示。

输入框演示