Hoppa till huvudinnehåll

Hur sparar jag och stänger arbetsboken efter inaktivitet under en viss tid?

I vissa tider kan du av misstag stänga en arbetsbok när du är upptagen med andra affärer under lång tid, vilket kan förlora viktiga data i arbetsboken. Finns det några knep för att automatiskt spara och stänga arbetsboken om du har inaktiverat den under en viss tid?

Spara automatiskt och stäng arbetsboken efter inaktivitet under en viss tid med VBA

pil blå höger bubbla Spara automatiskt och stäng arbetsboken efter inaktivitet under en viss tid med VBA

Det finns ingen inbyggd funktion i Excel för att lösa detta problem, men jag kan införa en makrokod som kan hjälpa dig att spara och stänga arbetsboken efter inaktivitet under en viss tid.

1. Aktivera arbetsboken som du vill spara och stänga automatiskt efter inaktivitet i vissa sekunder och tryck på Alt + F11 nycklar för att öppna Microsoft Visual Basic för applikationer fönster.

2. klick Insert > Modulerna att skapa en Modulerna och klistra in koden nedan. Se skärmdump:

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 spara nära arbetsbok efter inaktivitet 1

3. Sedan i Project Explorer dubbelklicka Den här arbetsbokenoch klistra in under koden i bredvid skriptet. Se skärmdump:

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 spara nära arbetsbok efter inaktivitet 2

4. Gå till dubbelklicka på modulen som du satte in i steg 2 och tryck på F5 för att köra koden. Se skärmdump:
doc spara nära arbetsbok efter inaktivitet 3

5. Sedan dyker det upp efter 15 sekunder en dialogruta som påminner dig om att du sparar arbetsboken och klickar på Ja för att spara och stänga arbetsboken.
doc spara nära arbetsbok efter inaktivitet 4

Tips:

(1) I den första koden kan du ändra inaktivitetstiden till annan i den här strängen: Nu + tidsvärde ("00:00:15")

(2) Om du aldrig har sparat arbetsboken tidigare, Spara som dialogrutan kommer först ut och ber dig spara den.
doc spara nära arbetsbok efter inaktivitet 5


god Skydda kalkylbladet

Kutools för Excel Skydda kalkylbladet funktionen kan snabbt skydda flera ark eller hela arbetsboken samtidigt.
doc skydda flera kalkylblad

Bästa kontorsproduktivitetsverktyg

🤖 Kutools AI Aide: Revolutionera dataanalys baserat på: Intelligent utförande   |  Generera kod  |  Skapa anpassade formler  |  Analysera data och generera diagram  |  Anropa Kutools funktioner.
Populära funktioner: Hitta, markera eller identifiera dubbletter   |  Ta bort tomma rader   |  Kombinera kolumner eller celler utan att förlora data   |   Rund utan formel ...
Superuppslag: Flera kriterier VLookup    VLookup med flera värden  |   VSök över flera ark   |   Fuzzy Lookup ....
Avancerad rullgardinslista: Skapa snabbt en rullgardinslista   |  Beroende rullgardinslista   |  Flervals-rullgardinslista ....
Kolumnhanterare: Lägg till ett specifikt antal kolumner  |  Flytta kolumner  |  Växla synlighetsstatus för dolda kolumner  |  Jämför intervall och kolumner ...
Utvalda funktioner: Rutnätsfokus   |  Designvy   |   Stor formelbar    Arbetsbok & Bladhanterare   |  Resursbibliotek (Automatisk text)   |  Datumväljare   |  Kombinera arbetsblad   |  Kryptera/Dekryptera celler    Skicka e-postmeddelanden efter lista   |  Superfilter   |   Specialfilter (filtrera fet/kursiv/genomstruken...) ...
Topp 15 verktygssatser12 text verktyg (lägga till text, Ta bort tecken, ...)   |   50+ Diagram Typer (Gantt Chart, ...)   |   40+ Praktiskt Formler (Beräkna ålder baserat på födelsedag, ...)   |   19 Införande verktyg (Infoga QR-kod, Infoga bild från sökväg, ...)   |   12 Konvertering verktyg (Siffror till ord, Valutaväxling, ...)   |   7 Slå ihop och dela verktyg (Avancerade kombinera rader, Dela celler, ...)   |   ... och mer

Uppgradera dina Excel-färdigheter med Kutools för Excel och upplev effektivitet som aldrig förr. Kutools för Excel erbjuder över 300 avancerade funktioner för att öka produktiviteten och spara tid.  Klicka här för att få den funktion du behöver mest...

Beskrivning


Fliken Office ger ett flikgränssnitt till Office och gör ditt arbete mycket enklare

  • Aktivera flikredigering och läsning i Word, Excel, PowerPoint, Publisher, Access, Visio och Project.
  • Öppna och skapa flera dokument i nya flikar i samma fönster, snarare än i nya fönster.
  • Ökar din produktivitet med 50 % och minskar hundratals musklick för dig varje dag!
Comments (11)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
When I don't want to edit and I just want to consult, the file still closes. It shouldn't close. Should restart counting when I select cells. What is the solution?
This comment was minimized by the moderator on the site
When I don't want to edit and I just want to consult, the file still closes. It shouldn't close. Should restart counting when I select cells. What is the solution?
This comment was minimized by the moderator on the site
This is great. Any tips on adding a popup message box that will warn the user the sheet is about to close and give them the option to reset the timer?
This comment was minimized by the moderator on the site
I'm not sure what happened but this solution no longer works. Here is the fix to this solution that worked for me:

````
Dim resetCount As Long

Public Sub Workbook_Open()
On Error Resume Next
Set xWB = ThisWorkbook
resetCount = 0
End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)On Error Resume Next
Reset
End Sub

Sub Reset()On Error Resume Next
Static xCloseTime
If resetCount <> 0 Then
ThisWorkbook.Application.OnTime xCloseTime, "SaveWork1", Schedule:=False
resetCount = resetCount + 1
xCloseTime = DateAdd("n", 15, Now)
ThisWorkbook.Application.OnTime xCloseTime, "SaveWork1", Schedule:=True

Else
resetCount = resetCount + 1
xCloseTime = DateAdd("n", 15, Now)
ThisWorkbook.Application.OnTime xCloseTime, "SaveWork1", Schedule:=True
End If
End Sub
````
This is using the same SaveWork1 As:
````Sub SaveWork1()
Application.DisplayAlerts = False
ThisWorkbook.Save
ThisWorkbook.Close

Application.DisplayAlerts = True
End Sub

````
This comment was minimized by the moderator on the site
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: - corrected and tested from the below comment - use this code:

Enter into "This Workbook"

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


Enter into "module":

Dim CloseTime As Date
Sub TimeSetting()
CloseTime = Now + TimeValue("00:10:00")
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()
ThisWorkbook.Close Savechanges:=True
End Sub


you can change the time setting by changing CloseTime = Now + TimeValue("00:10:00") - this is set to 10 minutes, change the("00:10:00") to whatever time you want and it works.
This comment was minimized by the moderator on the site
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
This comment was minimized by the moderator on the site
brilliant thanks
This comment was minimized by the moderator on the site
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
This comment was minimized by the moderator on the site
I sometimes run into a "Running time Error" when open the workbook that has this code built into it. Anyway to write this code better for it to be more stable?
This comment was minimized by the moderator on the site
I noticed the same thing. And found the same solution :-)
This comment was minimized by the moderator on the site
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.
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations