How to run an Excel personal VBA macro from Java with Jacob

折月煮酒 提交于 2019-12-22 01:27:42

问题


This code runs a macro if it is in the Excel file. It no longer runs a personal macro knowing this macro works fine manually.

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",
                new Variant(file.getName() + 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();
    }

}

I call this function to run a macro in the Excel file.

final File file = new File( "D:\\essay1.xlsm");
        final String macroName = "!Module1.Macro2";
        callExcelMacro(file, macroName);

How do I run a personal macro?


回答1:


Omit the module name - don't think that's needed



来源:https://stackoverflow.com/questions/31369709/how-to-run-an-excel-personal-vba-macro-from-java-with-jacob

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!