Excel VSTO,工作簿公开事件未触发

时间:2014-07-11 07:58:26

标签: vb.net excel vsto

我在VB.Net中的Excel Addin Proect中得到了以下代码:

Public Class ThisAddIn

    Private Sub Application_WorkbookOpen(Wb As Microsoft.Office.Interop.Excel.Workbook) Handles Application.WorkbookOpen
        Beep()
        MsgBox("fad")
    End Sub
End Class

这是由VB编辑器生成的。它是打开工作簿时的事件处理程序。当我按F5并运行代码时,显然事件处理程序不会执行。任何想法?

编辑:如果我从打开的工作簿中打开工作簿,但不会为原始工作簿本身运行,则会运行事件处理程序。

1 个答案:

答案 0 :(得分:1)

嗯,您知道Excel启动时不会调用打开事件,只有在打开现有工作簿时才会调用该事件。

有一个事件** NewWorkbook *有趣的是没有被解雇......

我找到了一种方法来解决这个问题,但不得不说我只测试了1分钟,试一试让我们知道

Public Class ThisAddIn
    Private Sub ThisAddIn_Startup() Handles Me.Startup
        AddHandler Globals.ThisAddIn.Application.WorkbookOpen, AddressOf MyWorkbookOpenEvent
        AddHandler Globals.ThisAddIn.Application.NewWorkbook, AddressOf MyNewWorkbookEvent
        If Globals.ThisAddIn.Application.Workbooks.Count = 1 Then MyWorkbookOpenEvent(Globals.ThisAddIn.Application.Workbooks(1))
    End Sub

    Private Sub MyWorkbookOpenEvent(ByVal Wb As Microsoft.Office.Interop.Excel.Workbook)
        System.Windows.Forms.MessageBox.Show("OPEN workbook event")
    End Sub

    Private Sub MyNewWorkbookEvent(ByVal Wb As Microsoft.Office.Interop.Excel.Workbook)
        System.Windows.Forms.MessageBox.Show("NEW Workbook event")
    End Sub

    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown
        RemoveHandler Globals.ThisAddIn.Application.WorkbookOpen, AddressOf MyWorkbookOpenEvent
        RemoveHandler Globals.ThisAddIn.Application.NewWorkbook, AddressOf MyNewWorkbookEvent
    End Sub
End Class