1

我正在使用 Window 7 SP1 和 MS Office 2010。我在 Access 2010 中运行查询,并将结果写入 Excel 2010 的报告中,并注意到 Excel 的实例不会从进程列表中终止。为了确保它不是我的代码,我已经把它剥离了基础。

  1. 以下代码按预期打开并终止 Excel:

    Public Sub Test()
        Dim strRptDirPath As String: strRptDirPath = "C:\Projects\WeeklyAlarms\Report\"
        Dim xlApp As Object
     '   Dim xlWkBk As Object
     '   Dim xlWkSht As Object
        Dim strRptTl As String: strRptTl = "Report Template.xls"
        Dim strRptSht As String: strRptSht = "Rpt"
    
        Set xlApp = CreateObject("Excel.Application")
            xlApp.Visible = False
    
    '    Set xlWkBk = xlApp.Workbooks.Open(strRptDir & strRptTl)
    '    Set xlWkSht = xlWkBk.Worksheets(strRptSht)
    '
    '        xlWkSht.Cells(1, 1).Value = "TEST 1"
    '        xlWkSht.Cells(2, 2).Value = "TEST 2"
    '        xlWkSht.Cells(3, 3).Value = "TEST 3"
    '
    '        xlWkBk.SaveAs (strRptDirPath & "TESTING.xls")
    '        xlWkBk.Close
            xlApp.Quit
    
    '    Set xlWkSht = Nothing
    '    Set xlWkBk = Nothing
        Set xlApp = Nothing
    
    End Sub
    
  2. 但是,如果我引用工作簿,Excel 流程实例不会终止。对谈话主题的搜索引用了在 Access 关闭后一段时间“ping”超时后终止的进程——这里不是这种情况。

    Public Sub Test()
        Dim strRptDirPath As String: strRptDirPath = "C:\Projects\WeeklyAlarms\Report\"
        Dim xlApp As Object
        Dim xlWkBk As Object
    '   Dim xlWkSht As Object
        Dim strRptTl As String: strRptTl = "Report Template.xls"
        Dim strRptSht As String: strRptSht = "Rpt"
    
        Set xlApp = CreateObject("Excel.Application")
            xlApp.Visible = False
    
        Set xlWkBk = xlApp.Workbooks.Open(strRptDir & strRptTl)
    '    Set xlWkSht = xlWkBk.Worksheets(strRptSht)
    '
    '        xlWkSht.Cells(1, 1).Value = "TEST 1"
    '        xlWkSht.Cells(2, 2).Value = "TEST 2"
    '        xlWkSht.Cells(3, 3).Value = "TEST 3"
    
            xlWkBk.SaveAs (strRptDirPath & "TESTING.xls")
            xlWkBk.Close
            xlApp.Quit
    
    '   Set xlWkSht = Nothing
       Set xlWkBk = Nothing
       Set xlApp = Nothing
    
    End Sub
    

我已取消选中 Microsoft Excel 14.0 对象库参考。我认为我没有进行任何全球参考电话。我看不到我做错了什么。

4

1 回答 1

0

尝试将xlWkBk.SaveAs (strRptDirPath & "TESTING.xls")行后的所有内容替换为:

If Not xlWkBk Is Nothing Then
    xlWkBk.Save
    xlWkBk.Close
    Set xlWkBk = Nothing
End If
If Not xlApp Is Nothing Then
    xlApp.Quit
    Set xlApp = Nothing
End If

像这样设置它确保了一切都按预期关闭

于 2015-02-17T07:12:22.640 回答