lockingExcel电子表格

我已经在Outlook VBA中编写了一个程序,该程序根据Excel电子表格的内容创build一些电子邮件。 这一切工作正常,但当程序终止我继续有一个“EXCEL.EXE”进程运行locking电子表格,让别人可以打开它。

在代码中,我有三个Excel对象:

Dim xl As Excel.Application Dim xlwb As Excel.Workbook Dim xlsheet As Excel.Worksheet 

最后,我closures工作簿并将所有variables设置为Nothing:

 xlwb.Close Set xlsheet = Nothing Set xlwb = Nothing Set xl = Nothing 

我错过了什么?

编辑:

这是代码的最基本的部分,包括新的“退出”行:

 Dim xl As Excel.Application Dim xlwb As Excel.Workbook Dim xlsheet As Excel.Worksheet Dim ol As Outlook.Application Dim Mail As MailItem Set xl = Excel.Application Set ol = Outlook.Application Set xlwb = xl.Workbooks.Open("C:\sheet.xlsx", ReadOnly) For Each xlsheet In xlwb.Worksheets for xlrow = 1 to 5 If xlsheet.Cells(xlRow, 1).Value = "John" Then msg=msg & xlsheet.Cells(xlRow, 2).Value end if next next Set Mail = ol.CreateItem(olMailItem) Mail.To = "A@bc" Mail.Subject = "John's email" Mail.Body = msg Mail.Send xlwb.Close xl.Quit Set ol = Nothing Set xlsheet = Nothing Set xlwb = Nothing Set xl = Nothing 

 xl.quit 

这将closures应用程序(您只closures工作簿,而不是代码中的应用程序),因此只需在将该variables设置为空之前将其置于此位置即可。

编辑:请将您的分支更改为以下内容:

 Dim xl As New Excel.Application Dim xlwb As Excel.Workbook Dim xlsheet As Excel.Worksheet Dim ol As Outlook.Application Dim Mail As MailItem Set ol = Outlook.Application Set xlwb = xl.Workbooks.Open("C:\sheet.xlsx", ReadOnly) For Each xlsheet In xlwb.Worksheets For xlRow = 1 To 5 If xlsheet.Cells(xlRow, 1).Value = "John" Then msg = msg & xlsheet.Cells(xlRow, 2).Value End If Next Next Set Mail = ol.CreateItem(olMailItem) Mail.To = "A@bc" Mail.Subject = "John's email" Mail.Body = msg Mail.Send xlwb.Close xl.Quit Set ol = Nothing Set xlsheet = Nothing Set xlwb = Nothing Set xl = Nothing 

你需要退出应用程序xl.Quit Set "" = Nothing是不是真的有必要

你可以尝试这样的事情

 Option Explicit Sub Excel() '// Declare variables Dim xlApp As Excel.Application Dim xlWb As Excel.Workbook Dim xlSheet As Excel.Worksheet Dim xlStarted As Boolean On Error Resume Next Set xlApp = GetObject(, "Excel.Application") If Err <> 0 Then Application.StatusBar = "Please wait while Excel source is opened ... " Set xlApp = CreateObject("Excel.Application") xlStarted = True End If ' your code here '// Close & SaveChanges xlWb.Close SaveChanges:=True If xlStarted Then xlApp.Quit End If '// clean up Set xlApp = Nothing Set xlWb = Nothing Set xlSheet = Nothing End Sub