HOW TO:控制是否允许用户退出ExcelApplication的Workbook
Posted on 2006-12-21 09:39 水如烟(LzmTW) 阅读(1648) 评论(3) 编辑 收藏 举报Author:水如烟
程序中若打开了一个Workbook给用户直接操作,那么,用户有可能将Workbook关闭了甚至退出了整个ExcelApplicatoin。可以通过以下方法防止这种情形(这个问题留意的人较少,故发首页):
Imports Microsoft.Office.Interop
Public Class Form1
Private gWorkbookCanClose As Boolean = False
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ExcelApplication As New Excel.Application
Dim Workbook As Excel.Workbook = ExcelApplication.Workbooks.Add
AddHandler Workbook.BeforeClose, AddressOf OnWorkbookBeforeClose
Dim Worksheet As Excel.Worksheet = CType(Workbook.Sheets.Add, Excel.Worksheet)
With CType(Worksheet.Cells(1, 1), Excel.Range)
.Interior.ColorIndex = 40
.Value = "123"
End With
ExcelApplication.Visible = True
End Sub
Private Sub OnWorkbookBeforeClose(ByRef cancel As Boolean)
cancel = Not gWorkbookCanClose
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
gWorkbookCanClose = Not gWorkbookCanClose
End Sub
End Class
Public Class Form1
Private gWorkbookCanClose As Boolean = False
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ExcelApplication As New Excel.Application
Dim Workbook As Excel.Workbook = ExcelApplication.Workbooks.Add
AddHandler Workbook.BeforeClose, AddressOf OnWorkbookBeforeClose
Dim Worksheet As Excel.Worksheet = CType(Workbook.Sheets.Add, Excel.Worksheet)
With CType(Worksheet.Cells(1, 1), Excel.Range)
.Interior.ColorIndex = 40
.Value = "123"
End With
ExcelApplication.Visible = True
End Sub
Private Sub OnWorkbookBeforeClose(ByRef cancel As Boolean)
cancel = Not gWorkbookCanClose
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
gWorkbookCanClose = Not gWorkbookCanClose
End Sub
End Class