如何在不停止运行宏的情况下将工作簿保存在VBA中?

时间:2016-07-24 19:57:36

标签: excel vba excel-vba

我有使用application.ontime经过一定时间后调用此方法的VBA代码,

Sub run()

Worksheets("Sheet1").Calculate

Cells(2, 5).Value = Cells(2, 5).Value + 1

ActiveWorkbook.Save

End Sub   

但是,在ActiveWorkbook.Save行之后,宏才会停止运行。如何在保存工作簿后继续运行我的宏,或者在保存时调用宏?我使用excel 2013 btw

这是我的宏调用run:

Sub every30seconds()

runTime = Now + TimeValue("00:00:30")

Application.OnTime EarliestTime:=runTime, Procedure:="run", schedule:=True

If Cells(2, 5).Value = 2 Then
   Application.OnTime runTime, "run", , False
   Cells(2, 5).Value = Cells(2, 5).Value - 2
End If

End Sub

1 个答案:

答案 0 :(得分:1)

Application.Ontime方法不允许您安排将来多次发生的事情。它只允许你设置一次发生的东西。

我相信你所追求的代码是

Sub run()
    Worksheets("Sheet1").Calculate

    Cells(2, 5).Value = Cells(2, 5).Value + 1

    ActiveWorkbook.Save

    every30seconds
End Sub   

Sub every30seconds()
    If Cells(2, 5).Value <> 2 Then
        runTime = Now + TimeValue("00:00:30")

        Application.OnTime EarliestTime:=runTime, Procedure:="run", schedule:=True
    Else
        Cells(2, 5).Value = Cells(2, 5).Value - 2
    End If
End Sub