我试图想出一种在一段时间不活动后关闭excel文档的方法。我遇到的问题是,如果excel处于编辑模式,宏将不会执行。这将是一个多人可以访问的服务器上的工作簿,问题是有些人将其打开并忘记他们打开它,没有其他人可以编辑它因此需要这个。
我创建的VBA宏代码仅在用户未处于编辑模式时关闭Excel文档:
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
我知道这种请求有点违背逻辑,因为当某人处于编辑过程中时你不想让工作簿关闭,这就是为什么你不能在编辑模式下运行宏。但是,如果在某个设定的时间段过后,有任何方法可以设置一些代码来保存和关闭工作簿,那么在这种情况下我需要它。谢谢
答案 0 :(得分:2)
您需要放置以下代码并将文件保存为XLSM类型。重新打开文件以运行宏
将代码放在标准模块中
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
将代码放在Thisworkbook Module
中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