Excel VBA 应用程序事件触发了两次
Excel VBA application event triggered twice
我试图在单击“快速打印”按钮时根据工作表名称更改活动打印机,但是 App_WorkbookBeforePrint
事件被触发了两次。试过App_WorkbookBeforeClose
也触发了两次。我已经将 Error Trapping 更改为 Break on All Error,但似乎没有发生任何错误。
本工作簿:
Private XLApp As CExcelEvents
Private Sub Workbook_Open()
Set XLApp = New CExcelEvents
End Sub
Class 模块:
Option Explicit
Private WithEvents App As Application
Private Sub Class_Initialize()
Set App = Application
End Sub
Private Sub App_WorkbookBeforePrint(ByVal Wb As Workbook, Cancel As Boolean)
MsgBox Wb.FullName
assignPrinter
End Sub
模块:
Const printer1 As String = "Bullzip PDF Printer on Ne10:"
Const printer2 As String = "EPSONF7E8B5 (L565 Series) on Ne07:"
Public Sub assignPrinter()
Dim ws As Worksheet
Dim wsn As String
Set ws = ActiveWorkbook.ActiveSheet
wsn = ws.Name
Select Case wsn
Case "FGWIP"
Application.ActivePrinter = printer1
ws.PrintOut
Exit Sub
Case "Rework"
Application.ActivePrinter = printer2
ws.PrintOut
Exit Sub
Case Else
MsgBox "Else case."
Exit Sub
End Select
End Sub
更新:
使用 App_SheetActivate
而不是 App_WorkbookBeforePrint
来更改活动打印机并删除 ws.Printout
,如 Matley
所述
我重新创建了您的模块,我收到的唯一错误是在代码 Debug.Print assignPrinter 中,我将其中替换为 assignPrinter.
其余代码工作正常。 App_WorkbookBeforePrint没有触发两次。您可以在 App_WorkbookBeforePrint 中设置一个断点,然后查看堆栈以查看第二次触发 App_WorkbookBeforePrint。
我试图在单击“快速打印”按钮时根据工作表名称更改活动打印机,但是 App_WorkbookBeforePrint
事件被触发了两次。试过App_WorkbookBeforeClose
也触发了两次。我已经将 Error Trapping 更改为 Break on All Error,但似乎没有发生任何错误。
本工作簿:
Private XLApp As CExcelEvents
Private Sub Workbook_Open()
Set XLApp = New CExcelEvents
End Sub
Class 模块:
Option Explicit
Private WithEvents App As Application
Private Sub Class_Initialize()
Set App = Application
End Sub
Private Sub App_WorkbookBeforePrint(ByVal Wb As Workbook, Cancel As Boolean)
MsgBox Wb.FullName
assignPrinter
End Sub
模块:
Const printer1 As String = "Bullzip PDF Printer on Ne10:"
Const printer2 As String = "EPSONF7E8B5 (L565 Series) on Ne07:"
Public Sub assignPrinter()
Dim ws As Worksheet
Dim wsn As String
Set ws = ActiveWorkbook.ActiveSheet
wsn = ws.Name
Select Case wsn
Case "FGWIP"
Application.ActivePrinter = printer1
ws.PrintOut
Exit Sub
Case "Rework"
Application.ActivePrinter = printer2
ws.PrintOut
Exit Sub
Case Else
MsgBox "Else case."
Exit Sub
End Select
End Sub
更新:
使用 App_SheetActivate
而不是 App_WorkbookBeforePrint
来更改活动打印机并删除 ws.Printout
,如 Matley
我重新创建了您的模块,我收到的唯一错误是在代码 Debug.Print assignPrinter 中,我将其中替换为 assignPrinter.
其余代码工作正常。 App_WorkbookBeforePrint没有触发两次。您可以在 App_WorkbookBeforePrint 中设置一个断点,然后查看堆栈以查看第二次触发 App_WorkbookBeforePrint。