问题
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