我的Word宏使用以下代码打开和访问Excel工作簿:
Dim objExcel As New Excel.Application Dim exWb As Excel.Workbook Set exWb = objExcel.Workbooks.Open("C:\Folder\Filename.xls") ' Main procedure exWb.Close Set exWb = Nothing objExcel.Quit Set objExcel = Nothing
由于我仍在调试中,因此宏通常在到达“关闭”和“退出”命令之前就停止了,从而使Excel实例和工作簿在后台处于打开状态。
有时我可以通过打开任务管理器并结束任务来关闭它们,但是我怀疑那是最好的解决方案。我可以在Word中编写一个宏来关闭所有打开的工作簿并退出Excel的所有(后台)实例吗?
以下是处理此类异常的传统方法:
Sub MySub() Dim objExcel As Excel.Application, exWb As Excel.Workbook On Error GoTo Cleanup Set objExcel = New Excel.Application Set exWb = objExcel.Workbooks.Open("C:\Folder\Filename.xls") ' Main procedure Cleanup: If Err.number <> 0 Then MsgBox "Error " & Err.number & ": " & Err.Description If Not exWb Is Nothing Then exWb.Close False If Not objExcel Is Nothing Then objExcel.Quit End Sub