首页 > 解决方案 > Application.wait 没有在它被写入的地方执行

问题描述

我想在宏的两个语句之间延迟 10 秒。我正在使用 excel vba 向其他软件发出命令

使用 wsActive

ExportPath = "C:\"
sTempFileNamevbs = ExportPath & Trim(.Name) & ".vbs"
iFileNumvbs = FreeFile
Open sTempFileNamevbs For Output As #iFileNumvbs
Print #iFileNumvbs, "Set Processes = GetObject(" & Chr(34) & "winmgmts:" & Chr(34) & ").InstancesOf(" & Chr(34) & "Win32_Process" & Chr(34) & ")"
Print #iFileNumvbs, "For Each Process In Processes"
Print #iFileNumvbs, "If StrComp(Process.Name, " & Chr(34) & "abcd.exe" & Chr(34) & ", vbTextCompare) = 0 Then"
Print #iFileNumvbs, "With CreateObject(" & Chr(34) & "WScript.Shell" & Chr(34) & ")"
Print #iFileNumvbs, ".AppActivate Process.ProcessId"
orty = w.Cells(j, 4).Value

**'that time delay is executing here before running of below statements**

If (Trim(orty) = "this") Then

Print #iFileNumvbs, ".SendKeys " & Chr(34) & "{Esc}" & Chr(34) & ""
Print #iFileNumvbs, ".SendKeys " & Chr(34) & "+{F3}" & Chr(34) & ""
Print #iFileNumvbs, ".SendKeys " & Chr(34) & "{Esc}" & Chr(34) & ""
Print #iFileNumvbs, ".SendKeys " & Chr(34) & "+{F3}" & Chr(34) & ""
End If

inst = w.Cells(j, 15).Value
nsenfo = w.Cells(j, 1).Value
limitsl = w.Cells(j, 5).Value

Application.Wait (Now + TimeValue("0:00:10")) '这里不执行这个时间延迟

If (Trim(nsenfo) = "NSE") And (Trim(limitsl) = "SL") Then

Print #iFileNumvbs, ".SendKeys"; Spc(1); "" & Chr(34) & ""; "+{TAB 4}"; "" & Chr(34) & ""
Print #iFileNumvbs, ".SendKeys"; Spc(1); "" & Chr(34) & ""; w.Cells(j, 5).Value; "" & Chr(34) & ""

标签: vba

解决方案


此 VBA 宏生成不同的代码 (VBScript) 并将其存储在文件中。后来这个 VBScript 文件似乎是单独执行的。在 VBA 宏中等待的时间不会使 VBScript 代码变慢。

您在这里真正需要做的是丢弃所有创建和执行 VBS 文件的代码。所有这些工作都可以而且应该在 VBA 中完成。像这样 - 代码基本完全相同,但更少,因为它不需要写入文件的部分:

Dim Processes, Process As Variant
Dim Shell As Object

Set Processes = GetObject("winmgmts:").InstancesOf("Win32_Process")
Set Shell = CreateObject("WScript.Shell")

For Each Process In Processes
  If StrComp(Process.Name, "abcd.exe", vbTextCompare) = 0 Then
    Shell.AppActivate Process.ProcessId

    If Trim(w.Cells(j, 4).Value) = "this" Then
      Application.Wait Now + TimeValue("0:00:10")

      With Shell
        .SendKeys "{Esc}"
        .SendKeys "+{F3}"
        .SendKeys "{Esc}"
        .SendKeys "+{F3}"
      End If
    End If

    Exit For
  End If
Next

但是,如果您害怕进行这种更改,则可以Application.Wait从当前代码中删除该行,而是添加:

Print #iFileNumvbs, "WScript.Sleep(10000)"

将等待的指令添加到 VBScript 文件中。(WScript.Sleep 需要几毫秒)。


推荐阅读