从 VBA 执行和连接外部程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25551921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Executing and Interfacing with an External Program from VBA
提问by Pascal Galloway
Right, situation first:
对了,先说情况:
- I have an excel workbook containing macros which carry out various operations.List item
- The resulting data is used by an extenal program (MathCad), which then outputs data to a .txt file. The catch is that Excel needs to be closed down before this operation
- The same workbook contains another macro to read the .txt results back into the excel workbook
- 我有一个包含执行各种操作的宏的 excel 工作簿。列表项
- 结果数据由外部程序 (MathCad) 使用,然后将数据输出到 .txt 文件。问题是在此操作之前需要关闭 Excel
- 同一个工作簿包含另一个宏,用于将 .txt 结果读回 excel 工作簿
I would like to be able to issue some commands which carry out all these operations at the click of a button. So far I have this:
我希望能够发出一些命令,通过单击按钮来执行所有这些操作。到目前为止,我有这个:
Public Sub Execute_Mathcad()
Dim x As Variant
Dim Path As String
Dim File As String
'save application in current form (should be up to date)
ThisWorkbook.Save
'pause vb script so mathcad can run normally
Application.Wait (Now + TimeValue("0:00:20"))
'open the external program
Path = "C:\Program Files (x86)\Mathcad\Mathcad 15\mathcad.exe"
File = "C:\Users\blah\blah.xmcd"
x = Shell(Path + " " + File, vbNormalFocus)
'issue CTRL+F9 in active program - can the keystroke be issued through windows directly (this solves and saves the MathCad program)
SendKeys ("^{F9}")
'exit mathcad using VBA command
'import results (I have code for this)
End Sub
The main problem for me seems to be how to pause excel and allow the external program to run. It cannot run whilst excel is open since it has to pull data from the workbook for some reason?
对我来说,主要问题似乎是如何暂停 excel 并允许外部程序运行。它无法在 excel 打开时运行,因为它出于某种原因必须从工作簿中提取数据?
Secondly, how can you issue a keyboard shortcut in an external program (e.g. CTRL+F9)
其次,如何在外部程序中发出键盘快捷键(例如 CTRL+F9)
Thanks!
谢谢!
回答by RubberDuck
Write a bat or vbs file that will launch MathCad, Close Excel, and then relaunch Excel and execute the result import. Call the file from a shell command much like you're currently opening MathLab.
编写一个 bat 或 vbs 文件,将启动 MathCad,关闭 Excel,然后重新启动 Excel 并执行结果导入。从 shell 命令调用文件,就像您当前打开 MathLab 一样。