如何使用Jacob从Java运行Excel个人VBA宏 [英] How to run an Excel personal VBA macro from Java with Jacob

查看:463
本文介绍了如何使用Jacob从Java运行Excel个人VBA宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果该代码在Excel文件中,则它将运行一个宏.它不再运行个人宏,因为知道该宏可以手动正常工作.

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

}

我调用此函数在Excel文件中运行宏.

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);

如何运行个人宏?

推荐答案

省略模块名称-认为不需要

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

这篇关于如何使用Jacob从Java运行Excel个人VBA宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆