1

我有一个宏应该每 x 分钟运行一次,以将当前文件保存到指定位置。我使用此链接来帮助编写代码 -> VBA Macro On Timer 样式以每隔设定的秒数运行代码,即 120 秒

但是,当另一个 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
4

1 回答 1

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 事件停用计时器。

于 2013-11-12T21:04:07.563 回答