繁体   English   中英

如何仅在一段时间内运行 Excel VBA 宏

[英]How to Run Excel VBA Macros only for sometime

我开发了一个 excel 宏,它检查文件的特定目录,如果有匹配的文件,它将选择并执行宏,我的意思是,如果文件被创建/出现在目录中,我只想检查目录 5 分钟提到的目录它应该选择和处理,如果不抛出错误。 如何仅在特定时间运行宏。

Do

    If fso.FileExists("file") Then

        Exit Do
    End If

    DoEvents 'Prevents Excel from being unresponsive
    Application.Wait Now + TimeValue("0:00:01") 'wait for one second
Loop

MsgBox "file available"

这是在有限的时间内等待事件的典型方法:

Sub DualCriteria()
    Dim tStart As Date, tNow As Date
    msg = ""
    tStart = Now

    Do
        DoEvents
        If Range("A1").Value <> "" Then
            msg = "event occured"
            Exit Do
        End If
        tNow = Now
        If tNow - tStart > TimeSerial(0, 5, 0) Then
            msg = "timeout"
            Exit Do
        End If
    Loop

  MsgBox msg
End Sub

宏等待用户在单元格A1 中输入一个值。 如果 5 分钟内没有任何反应,循环仍然会退出。

一条消息告诉您循环结束的原因。

笔记:

Doevents允许与工作表活动共享焦点。

请试试这个代码。 它等待 10 秒钟。 很容易适应您的需要。

Sub testFiniteLoop()
 Dim start As Date, fso As Object, fileName As String, boolFound As Boolean

 Set fso = CreateObject("Scripting.FileSystemObject")
 fileName = "C:\test.txt" ' use here your full file name
 start = Now
 Do While Now <= start + TimeValue("00:00:10")' use here what time you need

    If fso.FileExists(fileName) Then
        boolFound = True
        Exit Do
    End If

    DoEvents 'Prevents Excel from being unresponsive
    Application.Wait Now + TimeValue("0:00:01") 'wait for one second
 Loop

 MsgBox IIf(boolFound, "File available", "Checking time passed")
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM