任何工作簿打开时运行VBAmacros
我创build了一个Excel加载项,尝试在本会话期间打开的任何和所有工作簿打开时运行。 它有时有效 – 但并不总是,我不知道为什么。
我创build了一个文件addin.xlam
,并且在ThisWorkbook
中的这个文件中我有:
Private XLApp As CExcelEvents Private Sub Workbook_Open() Set XLApp = New CExcelEvents End Sub
然后我创build了一个基于代码的类模块: 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
如果我closures了Excel,并从Windows资源pipe理器中打开一个文件,这一行命中:
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
并启动代码 – 如果有问题的工作簿名称中包含“新报价”,macros将运行。 繁荣。 完善。
但是,在运行ONCE之后,如果我用“新报价单”打开另一个工作簿,则此专用分部不会触发。 为什么?
我每次打开任何工作簿时如何触发?
显然打开一个工作簿不会自动使其成为活动工作簿,至less在这个事件处理程序触发的时间。 尝试这个:
Private Sub App_WorkbookOpen(ByVal Wb As Workbook) If Not Wb Is Nothing Then If InStr(Wb.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
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
我不确定这是为什么 – 但是当我检查了“否”(所以我没有继续,因为我只是testing了这个),我在类模块中运行了End
,并且停止了Sub重新烧制直到我重新启动Excel。 删除这个End
代码现在允许Private Sub
每次打开工作簿…….怪异的。