关闭打开的 Excel 实例 [英] Close Open Excel Instance

查看:20
本文介绍了关闭打开的 Excel 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我以下简单的 VBScript 是否正确吗?它应该在其他进程运行后关闭 Excel(并保持 Excel 打开),但它不起作用.

Could someone please let me know if the following simple VBScript is correct? It is supposed to close Excel after other processes have run (and left Excel open), but it doesn't work.

Set MyApp = CreateObject("Excel.Application")
MyApp.Quit

推荐答案

CreateObject 创建一个新对象.如果我正确理解您的问题,您希望附加到已经运行的(孤立的)Excel 进程以终止它们.你可以用 GetObject 做到这一点:

CreateObject creates a new object. If I understand your question correctly you want to attach to already running (orphaned) Excel processes to terminate them. You can do that with GetObject:

On Error Resume Next
Do
  Set xl = GetObject(, "Excel.Application")
  status = Err.Number
  If status = 0 Then
    For Each wb in xl.Workbooks
      wb.Close False  'discard changes in open workbooks
    Next
    xl.Quit
  ElseIf status <> 429 Then
    WScript.Echo Err.Number & ": " & Err.Description
    WScript.Quit 1
  End If
Until status = 429
On Error Goto 0

请注意,这将尝试关闭所有正在运行的 Excel 实例,丢弃打开的工作簿中的所有更改.如果您希望它在打开的工作簿中保存更改,请将 Close 方法的参数更改为 True.如果您有想要继续运行的 Excel 实例,则需要添加代码以将它们排除在关闭之外.

Note that this will try to close all running Excel instances, discarding all changes in open workbooks. If you want it to save changes in open workbooks change the argument of the Close method to True. If you have Excel instances you want to keep running, you need to add code to exclude them from being closed.

另请注意,这不会强制终止无响应的实例.您需要为此终止该进程:

Note also, that this will not forcibly terminate unresponsive instances. You'd need to kill the process for that:

Set wmi = GetObject("winmgmts://root/cimv2")
For Each xl In wmi.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'excel.exe'")
  xl.Terminate
Next

这篇关于关闭打开的 Excel 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆