首页 > 解决方案 > 创建运行 Excel 的不需要的后台进程

问题描述

这是我第一次向 Stack Overflow 发布问题。

我正在开发一个 Word 宏,作为其过程的一部分,它在 Excel 工作簿中运行一个宏。据我所知,我的 Excel 宏中的代码按预期运行。我相信我的问题出现在我的 Word 宏代码中,我在这里展示的代码片段完全取自该来源。

这是 Word 宏代码的工作方式。它的代码首先确定 Excel 是否已打开(Excel 应用程序,而不是工作簿)。如果应用程序已经打开,我的代码会记下并连接到它。如果没有打开,我的代码会打开一个新的 Excel 应用程序。然后它会打开一个新的启用宏的工作簿并运行嵌入其中的指定宏。当 Excel 宏终止时,控制权返回到我的 Word 宏。该宏首先关闭 Excel 工作簿(而不是 Excel 应用程序)。然后,我的代码测试 Word 宏启动时 Excel 应用程序是否已经打开。如果是,Word 宏什么也不做;否则,它将关闭 Excel 应用程序。目标是在我的 Word 宏运行之前让用户的计算机处于其所处的状态(至少对于打开的 Excel 应用程序)。

对于以下测试场景,我的代码运行不正确。我从没有打开 Excel 应用程序的实例开始(作为应用程序或作为后台进程);我通过任务管理器验证了这一点。然后我运行以下代码过程:

'initiate the Excel session
excelAlreadyRunning = True
'Determine if Excel is already running
On Error Resume Next
Set ExcelApp = GetObject(, "Excel.Application") 'if Excel is not open, this code line throws an error
                                                'is Excel is open, ExcelApp will point at it after
                                                'execution of this line of code
If Err.Number = APPLICATION_NOT_OPEN Then       'not already running - start it and make it visible
        excelAlreadyRunning = False
        Set ExcelApp = CreateObject("Excel.Application")
        ExcelApp.Application.Visible = True
        Err.Clear
    Else
        ExcelApp.Application.Visible = True
End If

此代码按预期运行。我通过转到任务管理器来确认这一点。此代码完成后,将打开一个 Excel 应用程序,并且没有运行 Excel 的后台进程。

Excel 宏终止后,我在 Word 代码中达到以下几点:

'close the research tool
ExcelApp.ActiveWorkbook.Close SaveChanges:=False

'if Excel was not already running, close it and releases the resource
If Not excelAlreadyRunning = True Then
    ExcelApp.Application.Quit
    Set ExcelApp = Nothing
End If
Exit Sub

当执行到达 Set ExcelApp = Nothing 语句时,Excel 应用程序从任务管理器中消失了,但我现在有一个运行 Excel 的后台进程,而我之前没有。我再次通过任务管理器确认这一点。这个正在运行的后台进程会在我下次运行 Word 宏时出现问题,因为它检测到一个已经在运行的 Excel 应用程序,而应该没有。

问题是——为什么会发生这种情况,我该如何解决?我想也许我的 Excel 宏中可能有一个打开的用户窗体,但我找不到任何证据。此时,我看到的唯一解决方案是捕获打开的 Excel PID 并以这种方式关闭它。我宁愿不这样做,否则会导致其他问题。

标签: excelvbams-wordbackground-processtaskmanager

解决方案


推荐阅读