Excel和VBA可以控制外部应用程序如果他们有 COM 接口- 也就是说,如果您可以将应用程序声明为对象,创建该对象的实例,并查看其方法和属性。
如果您可以为您的程序找到一个 COM 包装器,那么就这样做。
如果您不能...您将不会喜欢使用 I/O 流和 Windows Shell 对象来完成此操作,因为命令行 DOS 界面作为用户界面并不是特别友好,并且它们比当您尝试在 VBA 中将糕点工厂用作 API 时。
首先,您需要 Windows 脚本宿主对象模型公开的“WshShell”对象。您可以通过后期绑定来声明和实例化它,如下所示:
Dim objWshell As Object
Set objWshell = CreateObject("WScript.Shell")
But the correct method (which will give you Intellisense drop-downs of the properties and methods) is to use the 'Tools:References...' dialog to create a reference to the parent library, which is usually found at C:\Windows\System32\wshom.ocx
然后您可以将 Shell 对象声明为:
Dim objWshell As IWshRuntimeLibrary.WshShell
Set objWshell = New IWshRuntimeLibrary.WshShell
在 VBA 中运行命令行可执行文件并读取 I/O 流
:
这是一个打开命令窗口并运行命令行可执行文件的示例,为其提供命令行开关“-s”和封装在双引号中的参数。
请注意,我正在运行的可执行文件不是“regsvr32.exe” - 我的 shell 对象正在执行 cmd.exe,这是 I/O 流的源和接收器。
当然,您可以直接运行您的应用程序。它可能会起作用。但是,当您调用 .StdOut.ReadLine 或 .StdOut.ReadAll 时,输出流锁定或“挂起”您的调用函数及其 VBA 线程是很常见的 - 您已被警告。
With objWshell.Exec("CMD /K")
.StdIn.WriteBlankLines 3
.StdIn.WriteLine "C:"
.StdIn.WriteLine "CD C:\"
.StdIn.WriteLine "regsvr32.exe -s " & Chr(34) & "%LIBDIR%\FXPricer.dll" & Chr(34)
.StdIn.WriteBlankLines 1
Do Until .StdOut.AtEndOfStream
Debug.Print .StdOut.ReadLine
Loop
Do Until .StdErr.AtEndOfStream
Debug.Print .StdOut.ReadLine
Loop
.Terminate
End With
Share and Enjoy. And, as always, watch out for line breaks inserted by your browser (or by StackOverflow's textbox interface) in the source code samples.