使用Java中的JACOB运行个人宏

时间:2016-01-08 16:39:07

标签: java vba excel-vba jacob excel

Here之前已经问过这个问题,但它从未收到任何答案。

如果我将宏保存到特定(非个人宏)工作簿,那么我可以让宏运行。

打开Excel文件后,我无法使个人宏工作。它给了我错误。

com.jacob.com.ComFailException: Invoke of: Run Source: Microsoft Excel Description: Sorry, we couldn't find C:\Users\Me\Documents\!PERSONAL.XLSB. Is it possible it was moved, renamed or deleted?

逻辑表明该程序正在查找错误中声明的文件路径中的宏,但我对它为什么首先检查该文件路径感到有些困惑。此外,如果它检查错误的文件路径,我该如何让它指向正确的文件路径。

我的代码:

 public static void main(String[] args) throws IOException{
 final File file = new File( "path");
            final String macroName = "!PERSONAL.XLSB!Macro";
            callExcelMacro(file, macroName);


  }
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(true));

        final Dispatch workbooks = excel.getProperty("Workbooks")
                .toDispatch();
        final Dispatch workBook = Dispatch.call(workbooks, "Open",
                file.getAbsolutePath()).toDispatch();

        // Calls the macro
       final Variant result = Dispatch.call(excel, "Run", macroName);

        // 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();
    }

}

0 个答案:

没有答案