Excel VBA应用程序事件触发两次

问题描述 投票:0回答:1

我在单击“快速打印”按钮时尝试根据工作表名称更改活动打印机,但是,App_WorkbookBeforePrint事件会被触发两次。尝试App_WorkbookBeforeClose也触发了两次。我已经将错误陷阱更改为中断所有错误,但似乎没有发生错误。

的ThisWorkbook:

Private XLApp As CExcelEvents

Private Sub Workbook_Open()
  Set XLApp = New CExcelEvents
End Sub

课程模块:

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更改活动打印机并删除matley提到的ws.Printout

excel vba excel-addins
1个回答
1
投票

我重新创建了你的模块,我收到的唯一错误是在代码Debug.Print assignPrinter中,我用assignPrinter替换了它。

其余的代码工作正常。 App_WorkbookBeforePrint没有触发两次。您可以在App_WorkbookBeforePrint中设置断点,然后查看Stack以查看第二次触发App_WorkbookBeforePrint。

© www.soinside.com 2019 - 2024. All rights reserved.