VBA 脚本关闭除自身之外的每个 Excel 实例 [英] VBA script to close every instance of Excel except itself

查看:38
本文介绍了VBA 脚本关闭除自身之外的每个 Excel 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的错误处理函数中有一个子例程,它尝试关闭在每个 Excel 实例中打开的每个工作簿.否则,它可能会留在内存中并破坏我的下一个 vbscript.它还应该关闭每个工作簿, 不保存任何更改.

I have a subroutine in my errorhandling function that attempts to close every workbook open in every instance of Excel. Otherwise, it might stay in memory and break my next vbscript. It should also close every workbook without saving any changes.

Sub CloseAllExcel()
On Error Resume Next
    Dim ObjXL As Excel.Application
    Set ObjXL = GetObject(, "Excel.Application")
    If Not (ObjXL Is Nothing) Then
        Debug.Print "Closing XL"
        ObjXL.Application.DisplayAlerts = False
        ObjXL.Workbooks.Close
        ObjXL.Quit
        Set ObjXL = Nothing
    Else
        Debug.Print "XL not open"
    End If
End Sub

然而,此代码不是最佳的.例如,它可以在一个 Excel 实例中关闭 2 个工作簿,但是如果您打开 2 个 Excel 实例,它只会关闭 1 个.

This code isn't optimal, however. For example, it can close 2 workbooks in one instance of Excel, but if you open 2 instances of excel, it will only close out 1.

如何重写它以关闭所有 Excel而不保存任何更改?

How can I rewrite this to close all Excel without saving any changes?

如何在不关闭托管此脚本的 Access 文件的情况下为 Access 执行此操作?

How to do this for Access as well without closing the Access file that is hosting this script?

推荐答案

我刚刚在 Excel 和 Access 中尝试了以下操作:

I just tried the following with both Excel and Access :

Dim sKill As String

sKill = "TASKKILL /F /IM msaccess.exe"
Shell sKill, vbHide

如果把msaccess.exe改成excel.exe,excel会被杀掉.

If you change the msaccess.exe to excel.exe, excel will be killed.

如果您想对流程进行更多控制,请查看:

If you want a bit more control over the process, check out:

http://www.vbaexpress.com/kb/getarticle.php?kb_id=811

这篇关于VBA 脚本关闭除自身之外的每个 Excel 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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