gpt4 book ai didi

vba - 不活动后触发代码

转载 作者:行者123 更新时间:2023-12-02 11:37:57 33 4
gpt4 key购买 nike

我希望我的WB在不活动时间后触发一些代码(自然由我设置)。我只能找到在不活动时间后关闭 WB 的代码,但我希望代码执行其他操作,与关闭 WB 不同。我找到了关闭WB的代码:

此工作簿模块:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
stop_Countdown
ThisWorkbook.Save
End Sub
Private Sub Workbook_Open()
start_Countdown
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
stop_Countdown
start_Countdown
End Sub
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
stop_Countdown
start_Countdown
End Sub
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, _
ByVal Target As Excel.Range)
stop_Countdown
start_Countdown
End Sub

常规模块:

Option Explicit
Public Close_Time As Date
Sub start_Countdown()
Close_Time = Now() + TimeValue("00:00:10")
Application.OnTime Close_Time, "close_WB"
End Sub
Sub stop_Countdown()
Application.OnTime Close_Time, "close_WB", , False
End Sub
Sub close_wb()
ThisWorkbook.Close True
End Sub

我应该在代码的哪一部分引入我希望 WB 在不活动后执行的事件,而不是关闭 WB?

最佳答案

您需要在常规模块中进行更改。

您必须指定包含您要执行的操作的过程的名称,而不是在 Application.OnTime 函数调用中传递字符串 close_wb()

以下是帮助您入门的代码:

Option Explicit
Public Inactivity_Time As Date

Sub start_Countdown()
Inactivity_Time = Now() + TimeValue("00:00:10")
Application.OnTime Inactivity_Time, "my_procedure" ' <- Notice that I changed the name of the procedure here
End Sub

Sub stop_Countdown()
On Error Resume Next
Application.OnTime Inactivity_Time, "my_procedure", , False ' <- And here too.
On Error GoTo 0
End Sub

Sub my_procedure()
' The code to perform you event goes here
End Sub

请查看here有关 Application.OnTime 方法的更多详细信息。

编辑:经过一些测试,您似乎无法在 Workbook_BeforeClose 子过程中调用 stop_Countdown() :它会抛出一个错误。根据this post ,在您的工作簿模块中,您必须将过程 Workbook_BeforeClose 替换为以下过程:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Close_WB
End Sub

并添加以下过程:

Public Sub Close_WB()
stop_CountDown
ThisWorkbook.Close SaveChanges:=True
End Sub

关于vba - 不活动后触发代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34910550/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com