Question

I'm using Jacob to call a VB function that resides in a Macro in an Excel file.

Here is my code : [I pass the file and the vb function name as paramaters to the below java method]

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


        final Dispatch workbooks = excel.getProperty("Workbooks").getDispatch();
        //String    eventSink = null ;
        int id = Dispatch.get(workbooks, "Count").getInt();
        System.out.println("le nbre" + id);
        Dispatch.call(workbooks, "Add");
        Dispatch workBook = Dispatch.call(workbooks, "Open", file.getAbsolutePath()).toDispatch();
        //new DispatchEvents(sourceOfEvent, eventSink, progId)

        //new DispatchEvents(workBook, w , "Excel.Application");
        //System.out.println("le résultat"+eventSink);      

        //d.safeRelease();
        Variant V1 = new Variant( file.getName() + macroName);
        // Calls the macro
        final Variant result = Dispatch.call(excel, "Run", V1);

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

The code runs fine, but my problem is that I don't want to call the instrcution

Dispatch workBook = Dispatch.call(workbooks, "Open", file.getAbsolutePath()).toDispatch();

which displays me what the default macro executes (an Interface with input fields).

Is there a way to "Run" the VB function without "Opening" the Excel file ?

Thanks.

Was it helpful?

Solution

there is no way to execute a VBA function in an Excel workbook without opening the file...

Of course, you can prevent the AUto_open macro running by disabling events on the Excel Application object.

In Excel VBA we do this like so:

Application.enableevents=false

(frequently in conjunction with other settings like ScreenUpdating and DisplayAlerts)

in Java maybe you use:

excel.setProperty("EnableEvents", new Variant(false));

I hope that pointers you in the right direction (lol, boom boom !)

Philip

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top