2016-02-26 172 views
-2

我从vb.net窗体窗体应用程序打开excel文件。如何禁用excel关闭按钮?

然后vb.net代码在这个excel文件中做一些操作。

我希望用户在进行某些操作时不要通过单击excel关闭按钮来关闭该excel文件。

那么如何禁用excel关闭按钮?

+0

这里是VBA的解决方案。 http://www.ozgrid.com/forum/showthread.php?t=57334我需要vb.net解决方案! –

回答

0

是的,你可以做到这一点。您需要声明您的WorkBook对象WithEvents,以便您可以挂入BeforeClose事件。

这里是一个完整的工作示例。它取消了保存被点击Button2的,直到和代码实际上是保存并关闭此时它允许保存发生的工作簿:

进口Microsoft.Office.Interop

Public Class Form1 

    Private _xlApp As Excel.Application 
    Private WithEvents _xlBook As Excel.Workbook 
    Private _cancelClose As Boolean = True 

    Private Sub _xlBook_BeforeClose(ByRef Cancel As Boolean) Handles _xlBook.BeforeClose 
     Cancel = _cancelClose 
    End Sub 

    Private Sub Open_Click(sender As Object, e As EventArgs) Handles OpenFileButton.Click 
     Dim filename As String = "C:\Temp\Book1.xlsx" 
     _xlApp = New Excel.Application 
     _xlApp.DisplayAlerts = False 
     _xlApp.Visible = True 
     _xlBook = _xlApp.Workbooks.Open(filename) 

     Dim xlSheet As Excel.Worksheet = CType(_xlBook.Sheets(1), Excel.Worksheet) 
     xlSheet.Cells(1, 1) = "Hello World 2" 
    End Sub 

    Private Sub Close_Click(sender As Object, e As EventArgs) Handles CloseFileButton.Click 
     _cancelClose = False 
     _xlBook.Save() 
     _xlBook.Close() 
     _xlApp.Quit() 
     System.Runtime.InteropServices.Marshal.ReleaseComObject(_xlBook) 
     System.Runtime.InteropServices.Marshal.ReleaseComObject(_xlApp) 
    End Sub 
End Class 
+1

非常感谢!解决了。 –

+0

错误很明显“WithEvents在局部变量声明中无效”您必须在模块或类级别声明它,如我的示例 –

+0

您需要声明它为'Public','Private','Friend'等 –