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

查看:124
本文介绍了关闭打开的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天全站免登陆