简体   繁体   English

VBA后台代码查看电子表格打开了多长时间

[英]VBA background code to see how long the spreadsheet has been open

I want to write some VBA in a spreadsheet so that it will evaluate how long the spreadsheet has been open and once it hits a certain time point (say an hour), then it will warn the user that it will automatically close in 15 mins.我想在电子表格中写一些 VBA 以便它评估电子表格打开了多长时间,一旦达到某个时间点(比如一个小时),它就会警告用户它将在 15 分钟内自动关闭。

Has anyone done anything like this or seen it open?有没有人做过这样的事情或看到它打开? I have a tab called Reference where I can put an auto-open piece of code to log when they opened it but I want the spreadsheet to check unprompted at certain intervals how long the sheet has been opened for.我有一个名为 Reference 的选项卡,当他们打开它时,我可以在其中放置一段自动打开的代码来记录,但我希望电子表格以特定的时间间隔自动检查工作表打开的时间。

The purpose of this is I want to force a close where a user has accidentally left a spreadsheet open so it's important it isn't assessed based on user input.这样做的目的是我想强制关闭用户不小心打开电子表格的地方,因此重要的是不要根据用户输入对其进行评估。 Note - I don't care if they lose work, I just want to close the spreadsheet.注意 - 我不在乎他们是否失去工作,我只想关闭电子表格。

Any help is really appreciated.非常感谢任何帮助。

To schedule the call of a routine, use Application.OnTime .要安排例程的调用,请使用Application.OnTime To ensure that the routine is scheduled to "one hour after opening", create a Workbook-Open sub (in ThisWorkbook-Module) and put something like this into it:为确保例程安排在“打开后一小时”,请创建一个 Workbook-Open 子(在 ThisWorkbook-Module 中)并将以下内容放入其中:

Private Sub Workbook_Open()
    Application.OnTime DateAdd("h", 1, Now), InformUser
End Sub

This will call the Sub InformUser one hour after the Workbook was opened.这将在工作簿打开一小时后调用 Sub InformUser In this routine you could add another call to OnTime .在此例程中,您可以添加另一个对OnTime的调用。 However, you need to be a little bit careful how to inform the user.但是,您需要注意如何通知用户。 If you simple use MsgBox but the user is not reacting to that, the MsgBox-Window stays active and as it is a modal window, the code will not continue to run and the OnTime -procedure will never be triggered.如果您简单地使用MsgBox但用户对此没有反应,则 MsgBox-Window 保持活动状态,并且由于它是模态 window,代码将不会继续运行,并且永远不会触发OnTime过程。 It's not easy to create a MsgBox with a TimeOut (see Display a message box with a timeout value ), so maybe create a simple form and show it Non-Modal.创建带有 TimeOut 的 MsgBox 并不容易(请参阅显示具有超时值的消息框),因此可以创建一个简单的表单并将其显示为非模态。

Sub InformUser()
    InfoForm.Show modal:=False
    Application.OnTime DateAdd("n", 15, Now), ShutDown   ' "n": Minutes ("m" stands for months)
End Sub

Sub ShutDown
    ThisWorkbook.Close SaveChanges:=True   ' Or "False" if you don't want to save - use on your own risk...
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM