2

我正在使用 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函数?

谢谢。

4

1 回答 1

2

如果不打开文件,就无法在 Excel 工作簿中执行 VBA 函数...

当然,您可以通过禁用 Excel 应用程序对象上的事件来阻止 AUto_open 宏运行。

在 Excel VBA 中,我们这样做:

Application.enableevents=false

(经常与 ScreenUpdating 和 DisplayAlerts 等其他设置结合使用)

在 Java 中,也许你使用:

excel.setProperty("EnableEvents", new Variant(false));

我希望能指引你正确的方向(大声笑,繁荣繁荣!)

菲利普

于 2013-03-25T15:22:22.097 回答