如何实例化命名的 Excel.Application 对象以允许在意外情况发生后进行宏后垃圾回收
我是一个相对 VBA 新手,正在设计一个相当复杂的宏,它可以运行 10 秒到 10 分钟之间的任何时间,它的大部分工作是在由 Dim appDatabaseInstance = New Excel.Application 创建的另一个不可见的 Excel 实例中完成的。
。在代码执行过程中会使用许多函数和子例程,虽然我已尽力确保每当出现任何半可预测的错误时都会调用 appDatabaseInstance.Quit
,但我无法控制一件事——用户。
具体来说,如果用户确定程序已崩溃并保留转义,VBA 将中断执行,并且由于中断发生的方式,我的垃圾收集例程(我认为)最终都不会发生。
因此,如果我能够以某种可预测的方式命名我创建的实例,然后在创建新实例之前尝试找到现有实例并对其进行适当处理,我会更高兴。这样,即使不幸的应用程序实例保持打开状态,只要用户尝试涉及该程序的其他任何操作,它就会立即关闭(如果他们不这样做,那么一个实例不太可能在上下文中引起太多麻烦)。
有人有什么建议吗?
I'm a relative VBA novice, and designing a fairly complex macro that can run for anything between 10 seconds and 10 minutes, which does most of its work in another invisible instance of Excel created by Dim appDatabaseInstance = New Excel.Application
. There are a number of functions and subroutines that get used over the course of code execution, and whilst I've done my best to ensure that appDatabaseInstance.Quit
is called whenever anything semi-predictable goes wrong, there's one thing I can't control - the user.
Specifically, if a user decides the program has crashed and holds escape, VBA will break execution, and because of how the break took place, none of my garbage collection routines (I think) end up taking place.
As such, I'd be much happier if I could somehow name the instance I create in a predictable manner, and then attempt, before creating a new instance, to find an existing one and deal with it appropriately. That way even if an unfortunate application instance gets left open, it will get closed as soon as the user tries anything else involving the programme (and if they don't, then one instance is unlikely to cause too many headaches in the context).
Does anyone have any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 Application 对象的
EnableCancelKey
属性来确定当用户中断您的代码时会发生什么我建议您查看 迪克博客上关于 EnableCancelKey 的这篇文章。
总之,
EnableCancelKey
具有三种可能的设置:You can use the
EnableCancelKey
property of the Application object to determine what will happen when a user interrupts your codeI suggest you see this post on EnableCancelKey at Dick's Blog.
As a summary,
EnableCancelKey
has three possible settings:我以前也曾在 VBA 中做过类似的事情。 follow 方法将关闭除当前正在运行代码的进程之外的所有其他 excel 进程。 请记住在尝试运行此代码之前保存您的内容!
I've had to do something similar in VBA before. The follow method will close all other excel process except the one that is currently running the code. Please remember to save your stuff before attempting to run this code!