处理事件“Excel正在关闭”

时间:2014-03-07 11:19:42

标签: vb.net excel excel-vba vba

我有一个vb .net应用程序,它打开一个Excel文件并将值放入其中。但是如果用户(我必须假设他非常愚蠢:)),关闭工作簿,下次我的应用程序尝试将值放到文件中时,它将显示错误,因为没有打开excel文件。

如何阻止excel关闭,或者在excel关闭时禁用按钮?

我在Windows 7上使用Excel 2003

编辑:这是打开Excel的代码

Private Sub Open_button_Click(sender As Object, e As EventArgs) Handles Open_button.Click


    OpenFileDialog1.FileName = ""
    OpenFileDialog1.Filter = "Excel files (*.xls)|*.xls"
    OpenFileDialog1.ShowDialog()
    filePath = OpenFileDialog1.FileName
    If System.IO.File.Exists(filePath) Then
        oExcel = CreateObject("Excel.Application")
        oExcel.Visible = True
        oBook = oExcel.Workbooks.Open(filePath)


        oSheet = oBook.WorkSheets(1)
        oExcel.Sheets(1).Select()
        oExcel.ScreenUpdating = True
        xlDown = Microsoft.Office.Interop.Excel.XlDirection.xlDown
        xlUp = Microsoft.Office.Interop.Excel.XlDirection.xlUp
        Me.Activate()

    End If
End Sub

1 个答案:

答案 0 :(得分:2)

您可以添加事件处理程序来检测关闭事件并禁用处理程序中的按钮。 来自https://support.microsoft.com/en-us/kb/822750

Private EventDel_BeforeBookClose As Excel.AppEvents_WorkbookBeforeCloseEventHandler

然后在创建Excel对象后

EventDel_BeforeBookClose = New Excel.AppEvents_WorkbookBeforeCloseEventHandler( _
        AddressOf BeforeBookClose)
AddHandler xlApp.WorkbookBeforeClose, EventDel_BeforeBookClose

并添加一个子来处理事件

Private Sub BeforeBookClose(ByVal Wb As Excel.Workbook, ByRef Cancel As Boolean)