当前位置: 首页 > 教程 > VBA >

VBA事件

精华
小牛编辑
126浏览
2023-03-14

在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 ("这是一个双击事件触发提示")
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工作表后,会向用户显示一条消息,如以下屏幕截图所示。