这个问题是CSDN一个网友提出的,个人觉得有必要做一总结。问题大概是这样:当利用VB或者VB.net进行Office自动化开发时,有时必须知道用户做了什么操作,例如切换打开的文件,关闭了Excel程序,改变了单元格的内容等等。实际上,Office对象模型中有大量的事件,可以精细控制到单元格的改变、Sheet的切换、文件打开关闭、加载宏加载等等,通过使用这些事件,我们就可以知道打开的Office程序是否被关闭。
下面举一个Excel的例子(以VB.net为例),新建一个工程,添加对Excel的引用,然后在Form中声明如下变量:
Dim WithEvents objExcel As Excel.Application
Dim objWorkBook As Excel.Workbook
打开或激活Excel:
objExcel = New Excel.Application
objWorkBook = objExcel.Workbooks.Add
objExcel.Visible = True
然后就可以响应Excel对象的事件了,例如:
Private Sub objExcel_WorkbookBeforeClose(ByVal Wb As Excel.Workbook, ByRef Cancel As Boolean) Handles objExcel.WorkbookBeforeClose
Me.lstEvent.Items.Add("将要关闭:" & Wb.Name)
End Sub
Private Sub objExcel_WorkbookBeforeSave(ByVal Wb As Excel.Workbook, ByVal SaveAsUI As Boolean, ByRef Cancel As Boolean) Handles objExcel.WorkbookBeforeSave
Me.lstEvent.Items.Add("保存:" & Wb.Name)
End Sub
Private Sub objExcel_WorkbookOpen(ByVal Wb As Excel.Workbook) Handles objExcel.WorkbookOpen
Me.lstEvent.Items.Add("打开:" & Wb.Name)
End Sub
Private Sub objExcel_SheetChange(ByVal Sh As Object, ByVal Target As Excel.Range) Handles objExcel.SheetChange
Me.lstEvent.Items.Add("改变了:" & CType(Sh, Excel.Worksheet).Name & " 的 " & Target.Address)
End Sub
Me.lstEvent.Items.Add("将要关闭:" & Wb.Name)
End Sub
Private Sub objExcel_WorkbookBeforeSave(ByVal Wb As Excel.Workbook, ByVal SaveAsUI As Boolean, ByRef Cancel As Boolean) Handles objExcel.WorkbookBeforeSave
Me.lstEvent.Items.Add("保存:" & Wb.Name)
End Sub
Private Sub objExcel_WorkbookOpen(ByVal Wb As Excel.Workbook) Handles objExcel.WorkbookOpen
Me.lstEvent.Items.Add("打开:" & Wb.Name)
End Sub
Private Sub objExcel_SheetChange(ByVal Sh As Object, ByVal Target As Excel.Range) Handles objExcel.SheetChange
Me.lstEvent.Items.Add("改变了:" & CType(Sh, Excel.Worksheet).Name & " 的 " & Target.Address)
End Sub
运行界面如下: