[英]How to Activate a specific Workbook on non-VBA Excel Quit
I have a workbook ("CodeBook.xlsm") that runs code using a BeforeSave event. 我有一个工作簿(“ CodeBook.xlsm”),该工作簿使用BeforeSave事件运行代码。 When a user has multiple workbooks open and chooses to quit excel via File/Exit, the user is prompted whether to save workbooks, and if yes to CodeBook.xlsm, then the BeforeSave code is run.
当用户打开多个工作簿并选择通过File / Exit退出excel时,系统将提示用户是否保存工作簿,如果是,则保存到CodeBook.xlsm,然后运行BeforeSave代码。 The problem is, at that point the ActiveWorkbook may not be CodeBook.xlsm, unless that happens to be the workbook that the user was in when he/she selected Exit Excel.
问题在于,此时ActiveWorkbook可能不是CodeBook.xlsm,除非恰好是用户选择“退出Excel”时所在的工作簿。 If the user quit excel from another workbook, the BeforeSave code is running but the activeworkbook is some random file of the user, so all the references to specific worksheets and ranges in the BeforeSave code do not work.
如果用户从另一个工作簿中退出excel,则BeforeSave代码正在运行,但是activeworkbook是用户的一些随机文件,因此对BeforeWork代码中的特定工作表和范围的所有引用均不起作用。
I have tried various ways using a Static declaration to retain the name of CodeBook and workbook().activate to activate it when the application is quitting, but when BeforeSave runs, it can't pick up the name CodeBook anywhere, short of hard-coding the name into the code. 我尝试了多种方法,使用静态声明保留CodeBook和workbook()的名称。在应用程序退出时激活它,但是在运行BeforeSave时,它无法在任何地方使用CodeBook的名称,除了硬将名称编码为代码。
Any suggestions? 有什么建议么? How to retain a variable name in memory when there is no code running, but is there when a user initiates a quit excel, OR how to activate a specific workbook when Excel is quitting from a user command and not from application.quit.
当没有代码运行时如何在内存中保留变量名,但是当用户启动excel退出时如何在内存中保留变量名,或者当Excel从用户命令而不是从application.quit退出时如何激活特定的工作簿。 Using excel 2010.
使用Excel 2010。
I overcame this by including a reference to the specific workbook. 我通过添加对特定工作簿的引用来克服了这一问题。
For example, this code simply saves the date/time stamp in cell A1
of Sheet1
before closing the document. 例如,此代码仅在关闭文档之前将日期/时间戳保存在
Sheet1
单元格A1
中。 By adding ThisWorkbook
, it works on the specific workbook that the code resides in. If you don't add ThisWorkbook
then it will work on the active workbook when the user quits. 通过添加
ThisWorkbook
,它可以在代码所在的特定工作簿上运行。如果不添加ThisWorkbook
则当用户退出时它将在活动工作簿上运行。
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Now()
End Sub
Place this code in the ThisWorkbook
module. 将此代码放在
ThisWorkbook
模块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.