防止运行宏的多个实例

防止运行宏的多个实例

“如何避免运行多个宏实例”

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

相关内容