vba - 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 宏生成不同的代码 (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 需要几毫秒)。
推荐阅读
- google-chrome-extension - document.querySelector 对 Chrome 扩展中的 Web 可访问资源有过时的关闭吗?
- sql - 2021 年的 Excel ADODB 查询日期
- c# - 如何在统一 c# 中使随机音频每 30 秒播放一次
- power-bi-report-server - 在 power bi 报表服务器中仅以 CSV 格式导出
- java - String 对象引用变量实际存储了什么?
- java - Vaadin Java Spring Boot - 错误:找到 WebSecurityConfigurerAdapter 以及 SecurityFilterChain。请只选择一项
- linux - 无法将参数传递给使用 Visual Studio 2019 远程调试的 linux 程序
- java - 有没有办法改变最终静态常量,在不同的类中静态使用,而不实例化它的类?
- powerbi - 将 DAX 表达式表转换为标量
- ansible - Ansible:如何在剧本之间传递标签