每当打开任何工作簿时运行VBA宏

时间:2015-07-24 16:35:25

标签: excel vba excel-vba

我创建了一个Excel加载项,尝试在此会话期间打开的任何和所有工作簿的基础上运行。它有时会起作用 - 但并非总是如此,我不知道为什么。

我创建了一个文件addin.xlam,在此文件的ThisWorkbook中,我有:

Private XLApp As CExcelEvents

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

然后我根据这里的代码创建了一个类模块:http://www.cpearson.com/Excel/AppEvent.aspx

Private WithEvents App As Application

Private Sub Class_Initialize()
    Set App = Application
End Sub

Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
    If Not ActiveWorkbook Is Nothing Then
        If InStr(ActiveWorkbook.Name, "New Quote") Then
            quoteCheck = MsgBox("Do you want to run the Quote Generator?", vbYesNo, "Quote Generator")
            If quoteCheck = vbYes Then
                prepare
            Else
                End
            End If
        End If
    End If
End Sub

如果我关闭Excel并从Windows资源管理器中打开文件,则该行会命中:

Private Sub App_WorkbookOpen(ByVal Wb As Workbook)

启动代码 - 如果有问题的工作簿名称中包含“新引号”,则运行宏。繁荣。完美。

但是,在运行ONCE之后,如果我打开另一个带有“new quote”的工作簿,则不会触发此私有子。为什么呢?

如何在每次 打开任何工作簿时触发

2 个答案:

答案 0 :(得分:1)

显然,打开工作簿不会自动使其成为活动工作簿,至少在此事件处理程序触发时是这样。试试这个:

Robot

答案 1 :(得分:0)

Private WithEvents App As Application

Private Sub Class_Initialize()
    Set App = Application
End Sub

Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
    If Not ActiveWorkbook Is Nothing Then
    If InStr(ActiveWorkbook.Name, "New Quote") Then
        quoteCheck = MsgBox("Do you want to run the Quote Generator?", vbYesNo, "Quote Generator")
        If quoteCheck = vbYes Then
            prepare
        Else
            '/ End '/REMOVE THIS LINE <--------------
        End If
    End If
End If
End Sub

我不确定为什么会这样 - 但是当我检查“不”(因此我没有继续,因为我只是测试它)时,我在类模块中运行了End,阻止Sub重新开火,直到我重新启动Excel。现在删除此End代码允许每次打开工作簿时Private Sub触发.......很奇怪。