我们可以拥有可以作为 VBA 代码的触发器(开关)的工作簿事件(例如打开、关闭等)。
要在工作簿打开时按照说明进行操作,请转到 ThisWorkbook 并选择 Workbook:
默认情况下将添加 Workbook_Open 事件,并在打开工作簿时触发:
Private Sub Workbook_Open() End Sub
例如,如果我们添加以下指令,则打开工作簿时将显示对话框:
Private Sub Workbook_Open() MsgBox "Welcome" End Sub
要在关闭工作簿之前执行指令,请选择 BeforeClose:
Private Sub Workbook_BeforeClose(Cancel As Boolean) End Sub
通过将变量“Cancel”设置为 True 可以取消关闭工作簿。
以下是要求用户确认关闭工作簿的示例:
Private Sub Workbook_BeforeClose(Cancel As Boolean) '如果用户以 NO 响应,则变量 Cancel 将具有值 TRUE (这将取消关闭工作簿) If MsgBox("Do you really want to close this workbook ?", 36, "I confirm") = vbNo Then Cancel = True End If End Sub
此事件在保存工作簿之前立即发生:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) End Sub
通过将变量“Cancel”设置为 True 可以取消保存文件。
此事件发生在打印工作簿之前:
Private Sub Workbook_BeforePrint(Cancel As Boolean) End Sub
通过将变量“Cancel”设置为 True 可以取消打印文件。
保存工作簿后立即发生此事件:
Private Sub Workbook_AfterSave(ByVal Success As Boolean) End Sub
每次在工作簿中的工作表之间切换时都会发生此事件:
Private Sub Workbook_SheetActivate(ByVal Sh As Object) End Sub
在此示例中,活动工作表的名称显示在对话框中:
Private Sub Workbook_SheetActivate(ByVal Sh As Object) MsgBox "Name of Sheet : " & Sh.Name End Sub
双击工作表单元格时会发生此事件:
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) End Sub
例如,我们可以使用此事件向单元格添加填充颜色,具体取决于所选工作表:
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) If Sh.Name = "Sheet1" Then Target.Interior.Color = RGB(255, 108, 0) '橙色 Else Target.Interior.Color = RGB(136, 255, 0) '绿色 End If End Sub
该事件发生在鼠标右键单击之前:
Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) End Sub
每当工作表的内容发生更改时,都会发生此事件:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) End Sub
每当计算或重新计算工作表中的数据时,都会发生此事件:
Private Sub Workbook_SheetCalculate(ByVal Sh As Object) End Sub
每当电子表格中选定单元格范围的内容发生更改时,就会发生此事件:
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) End Sub
在此示例中,如果单元格 A1 为空,填充颜色会发生变化:
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) If Range("A1") = "" Then Target.Interior.Color = RGB(124, 255, 255) '蓝色 End If End Sub
每当将新工作表添加到工作簿时就会发生此事件:
Private Sub Workbook_NewSheet(ByVal Sh As Object) End Sub
单击链接(超文本)时会发生此事件:
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink) End Sub