0

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?

Community
  • 1
  • 1

1 Answers1

0

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

GlorianChris
  • 217
  • 4
  • 16