在 Microsoft Access 中使用 VBA 读取 Microsoft Excel 工作簿,然后正常关闭它

在 Microsoft Access 中使用 VBA 读取 Microsoft Excel 工作簿,然后正常关闭它

我几乎已经成功了。但是,我发现即使我的 VBA 程序已完成,Microsoft Excel 仍在后台打开(如任务管理器中所示)。如果我再次运行该程序,它会出错。如果我终止 Microsoft Excel 进程,那么我可以再次运行我的 VBA 程序而不会出错。

我已经包含了对 Microsoft Excel 16.0 对象库的引用。

这是我的代码:

Dim appExcel As Excel.Application
Dim myWorkbook As Excel.Workbook
Dim myWorksheet As Excel.Worksheet
Dim strFilePath As String
Dim strWorksheetName As String

'Open the file as read-only.
strFilePath = <Path to file>
Set appExcel = CreateObject("Excel.Application")
Set myWorkbook = appExcel.Workbooks.Open(strFilePath, , True)
appExcel.Visible = False

Set myWorksheet = myWorkbook.Sheets(<The name of the worksheet I'm interested in>)

<read stuff from the worksheet in the same fashion that I would if I were doing this in Excel itself>

'Close the workbook without saving any changes.
myWorkbook.Close False
'appExcel.Quit
'Set appExcel = Nothing

如果我取消注释“appExcel.Quit”或“set appExcel = Nothing”语句,这似乎并不重要。那么,有什么优雅的方法可以正确关闭工作簿,以便将其完全从内存中删除?

谢谢!

答案1

为了解决这个问题,您需要使用这些线路。

  • 关闭工作簿,不保存并退出 Excel:

     xlWB.Close True
     Set xlWB = Nothing
     XLapp.Quit
     Set XLapp = Nothing
    

  • 关闭、保存工作簿并退出 Excel:

    xlApp.Application.ScreenUpdating = True
     xlWB.Save
     xlWB.Close True
     xlapp.Quit
     Set xlapp = Nothing
    

答案2

由于您使用 关闭工作簿myWorkBook.Close False,因此您关闭了工作簿以及 Excel,因此最后两行和appExcel.Quit销毁 COM 对象不会执行。

相关内容