设置一个Excel Doc保存并closures一段时间后不活动

我试图想出一个方法来closures一个excel文件后一段时间的不活动。 我遇到的问题是,如果excel处于编辑模式,macros将不会执行。 这将是一个在多人可以访问的服务器上的工作簿,问题是有些人把它打开,忘记了它打开了,没有其他人可以编辑它,因此需要这个。

我创build了一个VBAmacros代码,只有在用户不处于编辑模式时才closuresexcel文档:

Sub OpenUp() Dim Start, Finish, TotalTime, TotalTimeInMinutes, TimeInMinutes Application.DisplayAlerts = True TimeInMinutes = 1 ' sets timer for 1 minutes If TimeInMinutes > 1 Then TotalTimeInMinutes = (TimeInMinutes * 60) - (1 * 60) ' times 60 seconds to "minutize"/convert time from seconds to minutes Start = Timer ' Sets the start time. Do While Timer < Start + TotalTimeInMinutes DoEvents ' Yield to other Excel processes. Loop Finish = Timer ' Set end time. TotalTime = Finish - Start ' Calculate total time. Application.DisplayAlerts = False MsgBox "You've had this file open for " & TotalTime / 60 & " minutes. You have 1 minute to save all your files before Excel closes" End If Start = Timer ' Sets the start time. Do While Timer < Start + (1 * 60) DoEvents ' Yield to other Excel processes. Loop Finish = Timer ' Set end time. TotalTime = Finish - Start ' Calculate total time. Application.DisplayAlerts = False ThisWorkbook.Save Application.Quit End Sub 

我知道这种请求有悖于逻辑,因为当某人处于编辑过程中时,您不希望工作簿closures,因此您无法在编辑模式下运行macros。 但是,如果在某段时间已经过去之后,有什么办法可以设置一些代码来保存和closures工作簿的话,那么在这种情况下我就需要它了。 谢谢

您需要放置以下代码并将文件保存为XLSMtypes。 重新打开文件运行macros

将代码放在标准模块中

 Option Explicit Public EndTime Sub RunTime() Application.OnTime _ EarliestTime:=EndTime, _ Procedure:="CloseWB", _ Schedule:=True End Sub Sub CloseWB() Application.DisplayAlerts = False With ThisWorkbook .Save .Close End With End Sub 

将代码放在本工作簿模块中

 Option Explicit Private Sub Workbook_Open() EndTime = Now + TimeValue("00:00:20") '~~> 20 Seconds RunTime End Sub 

将其放在每个工作表中检测工作表中的任何更改

 Private Sub Worksheet_Change(ByVal Target As Range) If EndTime Then Application.OnTime _ EarliestTime:=EndTime, _ Procedure:="CloseWB", _ Schedule:=False EndTime = Empty End If EndTime = Now + TimeValue("00:00:20") '~~> 20 Seconds RunTime End Sub 

我已经从这个网站得到了答案http://www.excelforum.com/excel-programming-vba-macros/600241-excel-vba-close-workbook-after-inactivity.html