Tip: Other languages are Google-Translated. You can visit the English version of this link.
Log in
x
or
x
x
Register
x

or

How to save and close workbook after inactivity for a certain amount of time?

In some times, you may accidently close a workbook when you are busy with other affairs for a long time which may lose some important data in the workbook. Is there any tricks to automatically save and close the workbook if you have inactivated it for a certain amount of time?

Auto save and close workbook after inactivity for a certain amount of time with VBA


arrow blue right bubble Auto save and close workbook after inactivity for a certain amount of time with VBA

There is no built-in function in Excel to solve this problem, but I can introduce a macro code which can help you to save and close workbook after inactivity in a certain time.

1. Enable the workbook you want to automatically save and close after inactivity for a certain seconds, and press Alt + F11 keys to open Microsoft Visual Basic for Applications window.

2. Click Insert > Module to create a Module script, and paste below code to it. See screenshot:

Dim CloseTime As Date
Sub TimeSetting()
    CloseTime = Now + TimeValue("00:00:15")
    On Error Resume Next
    Application.OnTime EarliestTime:=CloseTime, _
      Procedure:="SavedAndClose", Schedule:=True
End Sub
Sub TimeStop()
    On Error Resume Next
    Application.OnTime EarliestTime:=CloseTime, _
      Procedure:="SavedAndClose", Schedule:=False
 End Sub
Sub SavedAndClose()
    ActiveWorkbook.Close Savechanges:=True
End Sub

 

doc save close workbook after inactivity 1

3. Then in the Project Explorer pane, double click This Workbook, and paste below code to the beside script. See screenshot:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Call TimeStop
End Sub

Private Sub Workbook_Open()
    Call TimeSetting
End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
   Call TimeStop
   Call TimeSetting
End Sub

 

doc save close workbook after inactivity 2

4. Go to double click at the module you inserted in step 2, and press F5 key to run the code. See screenshot:
doc save close workbook after inactivity 3

5. Then after 15 seconds, there is a dialog popping out for remind you saving the workbook, and click Yes to save and close the workbook.
doc save close workbook after inactivity 4

Tips:

(1) In the first code, you can change the inactivity time to other in this string: Now + TimeValue("00:00:15")

(2) If you have never saved the workbook before, the Save As dialog box will come out firstly and ask you to save it.
doc save close workbook after inactivity 5


good Protect Worksheet

Kutools for Excel's Protect Worksheet function can quickly protect multiple sheets or the whole workbook at once.
doc protect multiple worksheets

Kutools for Excel Solves Most of Your Problems, and Increases Your Productivity by 80%

  • Reuse: Quickly insert complex formulas, charts and anything that you have used before; Encrypt Cells with password; Create Mailing List and send emails...
  • Super Formula Bar (easily edit multiple lines of text and formula); Reading Layout (easily read and edit large numbers of cells); Paste to Filtered Range...
  • Merge Cells/Rows/Columns without losing Data; Split Cells Content; Combine Duplicate Rows/Columns... Prevent Duplicate Cells; Compare Ranges...
  • Select Duplicate or Unique Rows; Select Blank Rows (all cells are empty); Super Find and Fuzzy Find in Many Workbooks; Random Select...
  • Exact Copy Multiple Cells without changing formula reference; Auto Create References to Multiple Sheets; Insert Bullets, Check Boxes and more...
  • Extract Text, Add Text, Remove by Position, Remove Space; Create and Print Paging Subtotals; Convert Between Cells Content and Comments...
  • Super Filter (save and apply filter schemes to other sheets); Advanced Sort by month/week/day, frequency and more; Special Filter by bold, italic...
  • Combine Workbooks and WorkSheets; Merge Tables based on key columns; Split Data into Multiple Sheets; Batch Convert xls, xlsx and PDF...
  • More than 300 powerful features. Supports Office/Excel 2007-2019 and 365. Supports all languages. Easy deploying in your enterprise or organization. Full features 30-day free trial.
kte tab 201905

Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!
officetab bottom
Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Rajesh rana · 6 months ago
    hi i want insert this code to an other code like expiration code with this code how i can do....?
    code is...following
    Private Sub Workbook_Open()

    Dim exdate As Date
    Dim i As Integer

    'modify values for expiration date here !!!
    anul = 2019 'year
    luna = 5 'month
    ziua = 16 'day

    exdate = DateSerial(anul, luna, ziua)

    If Date > exdate Then
    MsgBox ("The application " & ThisWorkbook.Name & " has expired !" & vbNewLine & vbNewLine _
    & "Expiration set up date is: " & exdate & " :)" & vbNewLine & vbNewLine _
    & "Contact Administrator to renew the version !"), vbCritical, ThisWorkbook.Name

    expired_file = ThisWorkbook.Path & "\" & ThisWorkbook.Name

    On Error GoTo ErrorHandler
    With Workbooks(ThisWorkbook.Name)
    If .Path <> "" Then

    .Saved = True
    .ChangeFileAccess xlReadOnly

    Kill expired_file

    'get the name of the addin if it is addin and unistall addin
    If Application.Version >= 12 Then
    i = 5
    Else: i = 4
    End If

    If Right(ThisWorkbook.Name, i) = ".xlam" Or Right(ThisWorkbook.Name, i) = ".xla" Then
    wbName = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - i)
    'uninstall addin if it is installed
    If AddIns(wbName).Installed Then
    AddIns(wbName).Installed = False
    End If
    End If

    .Close

    End If
    End With

    Exit Sub

    End If

    'MsgBox ("You have " & exdate - Date & "Days left")
    Exit Sub

    ErrorHandler:
    MsgBox "Fail to delete file.. "
    Exit Sub

    End Sub
  • To post as a guest, your comment is unpublished.
    seb · 10 months ago
    brilliant thanks
  • To post as a guest, your comment is unpublished.
    Torin · 10 months ago
    If you are working in a separate workbook at the point where close time is reached then it will close that workbook and not the inactive one. This can be solved by adjusting the code to:

    Dim CloseTime As Date
    Dim WKB As String
    Sub TimeSetting()
    WKB = ActiveWorkbook.Name
    CloseTime = Now + TimeValue("00:00:15")
    On Error Resume Next
    Application.OnTime EarliestTime:=CloseTime, _
    Procedure:="SavedAndClose", Schedule:=True
    End Sub
    Sub TimeStop()
    On Error Resume Next
    Application.OnTime EarliestTime:=CloseTime, _
    Procedure:="SavedAndClose", Schedule:=False
    End Sub
    Sub SavedAndClose()
    Workbooks(WKB).Close Savechanges:=True
    End Sub
    • To post as a guest, your comment is unpublished.
      Ro · 1 months ago
      I noticed the same thing. And found the same solution :-)
  • To post as a guest, your comment is unpublished.
    Excel · 2 years ago
    The above code is not working when a cell is active. That is

    1. enter a value in the cell (don't press Enter or tab)

    2. minimize the excel.

    In this case the code is not working.