中断工作(在任何活动文件中)每隔x分钟运行一次宏 - Excel VBA

时间:2013-11-12 20:21:37

标签: excel vba excel-vba autorun

我有一个宏,应该每隔x分钟运行一次,将当前文件保存到指定位置。我用这个链接来帮助编写代码 - > VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

但是,当另一个excel文件打开时,宏会被绊倒。有人正在研究它。

有没有办法打断用户的当前操作&使用消息框或其他东西通知他,以便宏可以继续吗?

Dim TimeToRun, k, RDNum, DestinationFolderName, MasterFile, TestCellNum

Sub ScheduleIt()
    TimeToRun = Now + TimeValue("00:00:10")
    Application.OnTime TimeToRun, "CopyPriceOver"
End Sub

Sub CopyPriceOver()
    Windows(MasterFile).Activate
    Worksheets("Save Log").Activate

    dt = Format(CStr(Now), "mm-dd-yyyy hh-mm-ss")
    MasterFileName = DestinationFolderName & "RD" & RDNum & " " & TestCellNum & " " & dt & ".xlsb"
    ActiveWorkbook.SaveAs Filename:=MasterFileName, FileFormat:=xlExcel12, CreateBackup:=False

    Call ScheduleIt
End Sub
Sub AutoOpen()
    k = 1
    Worksheets("Test Header").Activate
    RDNum = Range("C4").Value
    LR = Cells(Rows.Count, "I").End(xlUp).Row 'Sets the last row
    TestCellNum = Cells(LR, "I").Value
    DestinationFolderName = "\\C:\Directory\"
    MasterFile = ThisWorkbook.Name

    Call ScheduleIt
End Sub

Sub AutoClose()
    Application.OnTime TimeToRun, "CopyPriceOver", , False
End Sub

1 个答案:

答案 0 :(得分:0)

检查是否已激活预期的工作簿,因此仅对该工作簿执行保存操作:

Public Sub OnTimeCallback()
    If ActiveWorkbook.Name = "MyWorkbook.xlsm" Then
        Debug.Print "Save some stuff"
    End If
    alertTime = Now + TimeValue("00:0:02")
    Application.OnTime alertTime, "OnTimeCallback"
End Sub

更好的解决方案是,只要另一个工作簿处于活动状态,就可以使用Workbook_Activate / Workbook_Deactivate事件停用计时器。