【发布时间】:2013-03-25 10:10:04
【问题描述】:
我正在使用 Jacob 调用驻留在 Excel 文件中的宏中的 VB 函数。
这是我的代码:[我将文件和 vb 函数名称作为参数传递给下面的 java 方法]
private static void callExcelMacro(File file, String macroName) {
ComThread.InitSTA();
final ActiveXComponent excel = new ActiveXComponent("Excel.Application");
try {
// This will open the excel if the property is set to true
excel.setProperty("Visible", new Variant(false));
final Dispatch workbooks = excel.getProperty("Workbooks").getDispatch();
//String eventSink = null ;
int id = Dispatch.get(workbooks, "Count").getInt();
System.out.println("le nbre" + id);
Dispatch.call(workbooks, "Add");
Dispatch workBook = Dispatch.call(workbooks, "Open", file.getAbsolutePath()).toDispatch();
//new DispatchEvents(sourceOfEvent, eventSink, progId)
//new DispatchEvents(workBook, w , "Excel.Application");
//System.out.println("le résultat"+eventSink);
//d.safeRelease();
Variant V1 = new Variant( file.getName() + macroName);
// Calls the macro
final Variant result = Dispatch.call(excel, "Run", V1);
// Saves and closes
//Dispatch.call(workBook, "Save");
com.jacob.com.Variant f = new com.jacob.com.Variant(true);
// Dispatch.call(workBook, "Close", f);
} catch (Exception e) {
e.printStackTrace();
} finally {
excel.invoke("Quit", new Variant[0]);
ComThread.Release();
}
}
代码运行良好,但我的问题是我不想调用指令
Dispatch workBook = Dispatch.call(workbooks, "Open", file.getAbsolutePath()).toDispatch();
它向我展示了默认宏执行的内容(带有输入字段的界面)。
有没有办法在不“打开”Excel文件的情况下“运行”VB函数?
谢谢。
【问题讨论】:
-
当包含编译器(?)的应用程序没有启动时,VB代码将如何“运行”?
-
我的 Java 代码将动态调用 VB 函数(通过按钮)。所以正常的执行是:加载excel文件,运行宏并释放对象。希望我回答了你的问题。
-
打开 excel 并启用代码后,您还可以启用嵌入或由 Workbook_Open 触发的任何代码,我担心如果没有另一个 (Workbook_Open),您将无法拥有一个(您想要的脚本)跨度>
-
这是必须在打开工作簿之前设置的 Application EnableEvents 属性,以防止执行任何 Auto_open 或 WOrkbook OPen 事件,请参阅下面的答案...