代码的目标是查看计算机是否空闲。如果有足够的时间过去,则首先发出文件即将保存的警告,然后如果再过一段时间没有响应,则自动保存文件。但是,空闲计时器无法触发我的任何潜艇。当我刚刚自动保存时,它可以工作。
这是我在 ThisWorkbook 中的代码,用于自动运行我的 3 个潜艇。
Option Explicit
Sub Workbook_Open()
IdleTime
WarningMessage
CloseDownFile
End Sub
命名有点偏离,因为CloseDownFile
实际上并没有关闭文件,但我只是从未更改过名称。
这是运行良好的代码:
Private Type LASTINPUTINFO
cbSize As Long
dwTime As Long
End Type
Private Declare Sub GetLastInputInfo Lib "user32" (ByRef plii As LASTINPUTINFO)
Private Declare Function GetTickCount Lib "kernel32" () As Long
Function IdleTime() As Single
Dim a As LASTINPUTINFO
a.cbSize = LenB(a)
GetLastInputInfo a
IdleTime = (GetTickCount - a.dwTime) / 1000
End Function
Public Sub CloseDownFile()
On Error Resume Next
If IdleTime > 30 Then
Application.StatusBar = "Inactive File Closed: " & ThisWorkbook.Name
ThisWorkbook.Save
Else
CloseDownTime = Now + TimeValue("00:00:30") ' change as needed
Application.OnTime CloseDownTime, "CloseDownFile"
End If
End Sub
这些是我在模块 1 中的 3 个主要子组件,它们源于运行良好但现在计时器不工作的代码段。此外,现在 Option Explicit 已打开,表示未定义 CloseDownTime:
Option Explicit
Private Type LASTINPUTINFO
cbSize As Long
dwTime As Long
End Type
Private Declare Sub GetLastInputInfo Lib "user32" (ByRef plii As LASTINPUTINFO)
Private Declare Function GetTickCount Lib "kernel32" () As Long
Function IdleTime() As Single
Dim a As LASTINPUTINFO
a.cbSize = LenB(a)
GetLastInputInfo a
IdleTime = (GetTickCount - a.dwTime) / 1000
End Function
Public Sub CloseDownFile()
On Error Resume Next
If IdleTime > 30 Then
Application.StatusBar = "Inactive File Closed: " & ThisWorkbook.Name
ThisWorkbook.Save
Else
CloseDownTime = Now + TimeValue("00:00:30") ' change as needed
Application.OnTime CloseDownTime, "CloseDownFile"
End If
End Sub
Public Sub WarningMessage()
On Error Resume Next
If IdleTime > 20 Then
Application.StatusBar = "Saving File" & ThisWorkbook.Name
ShowForm
End If
End Sub
这是由 WarningMessage 调用的 ShowForm 子:
Option Explicit
Public Sub ShowForm()
Dim frm As New UserForm1
frm.BackColor = rgbBlue
frm.Show
End Sub
这是在 Userform1 中运行的代码:
Private Sub CommandButton1_Click()
Hide
m_Cancelled = True
MsgBox "Just Checking!"
CloseDownTime = Now + TimeValue("00:00:30")
Application.OnTime CloseDownTime, "WarningMessage"
End Sub
Private Sub Image1_Click()
End Sub
Private Sub CommandButton2_Click()
Hide
m_Cancelled = True
MsgBox "Then how did you respond?"
CloseDownTime = Now + TimeValue("00:00:30")
Application.OnTime CloseDownTime, "WarningMessage"
End Sub
Private Sub TextBox1_Change()
End Sub