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.
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.
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
. 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:
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. In this routine you could add another call to 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. 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.