VBA - 创建.vbs和.bat以向外部程序发出击键

时间:2014-09-01 13:57:50

标签: vba batch-file vbscript

我创建了一个创建两个文件的vba脚本。 .vbs文件用于打开外部程序并发送击键。该程序通过.bat文件调用。外部程序(Mathcad)打开,但它不会执行后面的操作(sendkeys)。我怎么能调试.vbs文件,除非有人能发现错误?

Public Sub Execute_Mathcad()

Dim ExportPath As String
Dim iFileNum As Long
Dim iFileNumvbs As Long
Dim wsActive As Worksheet
Dim sTempFileName As String
Dim sTempFileNamevbs As String

Set wsActive = ActiveSheet

ThisWorkbook.Save

'Create batch file
With wsActive

    'create .vbs file for keystrokes (called in .bat file)
    ExportPath = "C:\Temp\"
    sTempFileNamevbs = ExportPath & Trim(.Name) & ".vbs"
    iFileNumvbs = FreeFile
    Open sTempFileNamevbs For Output As #iFileNumvbs
    Print #iFileNumvbs, "Set WshShell = WScript.CreateObject(" & Chr(34) & "WScript.Shell" & Chr(34) & ")"
    Print #iFileNumvbs, "WshShell.Run(" & Chr(34) & "C:\Users\blah.xmcd" & Chr(34) & ")"
    Print #iFileNumvbs, "WScript.Sleep 10000"
    Print #iFileNumvbs, "WshShell.AppActivate"; Spc(1); "WshShell"
    Print #iFileNumvbs, "WScript.Sleep 5000"
    Print #iFileNumvbs, "WshShell.SendKeys"; Spc(1); """^{F9}"""

    'create .bat file
    sTempFileName = ExportPath & Trim(.Name) & ".bat"
    iFileNum = FreeFile
    Open sTempFileName For Output As #iFileNum
    Print #iFileNum, "@Echo off"
    Print #iFileNum, "wscript"; Spc(1); """C:\Temp\Results.vbs"""
End With

Close #iFileNum
Close #iFileNumvbs

'run batch file
retVal = Shell(sTempFileName, vbHide)

'this returns an error if sTempFileName is incorrect
If retVal = 0 Then
    MsgBox "An Error Occured"
    Close #FileNumber
    End
End If

'exit Excel using VBA command
Application.Quit

End Sub

1 个答案:

答案 0 :(得分:0)

代码已更正,现在可以使用了。感谢大家的投入。我确信有一个更简洁的解决方案,但这可以胜任!