📅  最后修改于: 2020-11-19 09:13:57             🧑  作者: Mango
VBA,当您手动更改单元格或单元格值范围时,可以触发事件驱动的编程。更改事件可能使事情变得容易,但是您可以非常快速地结束充满格式的页面。有两种事件。
当工作表中发生更改时,将触发工作表事件。通过在工作表选项卡上单击鼠标右键,然后选择“查看代码”,然后粘贴代码,可以创建该代码。
用户可以选择这些工作表中的每个工作表,然后从下拉列表中选择“ WorkSheet”以获取所有受支持的工作表事件的列表。
以下是用户可以添加的受支持的工作表事件。
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子过程显示给用户,如以下屏幕快照所示。
以下是用户可以添加的受支持的Workbook事件。
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工作表后,将向用户显示一条消息,如以下屏幕截图所示。