![防止运行宏的多个实例](https://linux22.com/image/1573451/%E9%98%B2%E6%AD%A2%E8%BF%90%E8%A1%8C%E5%AE%8F%E7%9A%84%E5%A4%9A%E4%B8%AA%E5%AE%9E%E4%BE%8B.png)
“如何避免运行多个宏实例”
Sub CallBot()
If Activesheet.Range("A1").Value = 1 Then
Call Bot
ElseIf Activesheet.Range("B1").Value = 1 Then
Call BotTwo
End If
Application OnTime + TimeValue("00:01:00")
End Sub
这会导致 CallBot 的多个实例运行(循环),但我只想每隔一分钟运行一次,请帮忙
还尝试了以下代码
Sub CallBot()
Dim TimeToRun
If Activesheet.Range("A1").Value = 1 Then
Call Bot
ElseIf Activesheet.Range("B1").Value = 1 Then
Call BotTwo
End If
Application OnTime + TimeValue("00:01:00")
End Sub
Sub Repeat()
If TimeToRun > 0 Then
Application.OnTime TimeToRun, "CallBot", False
End If
TimeToRun = Now + TimeValue("00:00:20")
Application.OnTime TimeToRun, "CallBot"
End Sub
答案1
只需设置一个全局变量来跟踪机器人是否计划运行:
Public botScheduled As Boolean
Sub CallBot()
If not botScheduled Then
If Activesheet.Range("A1").Value = 1 Then
Call Bot
botScheduled = True
ElseIf Activesheet.Range("B1").Value = 1 Then
Call BotTwo
botScheduled = True
End If
End If
End Sub
您尚未提供Bot
代码,但是当您的机器人代码完成时,您可以在那里设置botScheduled = False
。