2016-01-13 93 views
3

我有一個在Excel文件中定義的宏,我想使用Jacob 1.18 jar和dll從Java程序中調用它。使用Jacob從Java調用宏1.18

以下是我目前使用的代碼段。

import java.io.File; 

import com.jacob.activeX.ActiveXComponent; 
import com.jacob.com.ComThread; 
import com.jacob.com.Dispatch; 
import com.jacob.com.Variant; 


public class TestJacob { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     File file = new File("C:\\TestJacob\\TestExcel_copy.xlsm"); 
     String macroName = "TestMacro"; 
     callExcelMacro(file, macroName); 

    } 

    private static void callExcelMacro(File file, String macroName) { 
     ComThread.InitSTA(true); 
     final ActiveXComponent excel = new ActiveXComponent("Excel.Application"); 
     try{ 
      excel.setProperty("EnableEvents", new Variant(false)); 

      Dispatch workbooks = excel.getProperty("Workbooks") 
        .toDispatch(); 

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

      // Calls the macro 
      Variant V1 = new Variant(file.getName() + macroName); 
      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(); 
     } 
    } 
} 

以下是我在調用宏時遇到的異常。

com.jacob.com.ComFailException: Invoke of: Run 
Source: Microsoft Excel 
Description: Cannot run the macro 'TestExcel_copy.xlsmTestMacro'. The macro may not be available in this workbook or all macros may be disabled. 

    at com.jacob.com.Dispatch.invokev(Native Method) 
    at com.jacob.com.Dispatch.invokev(Dispatch.java:625) 
    at com.jacob.com.Dispatch.callN(Dispatch.java:453) 
    at com.jacob.com.Dispatch.call(Dispatch.java:541) 
    at TestJacob.callExcelMacro(TestJacob.java:38) 
    at TestJacob.main(TestJacob.java:16) 

我也通過以下步驟啓用了Excel文件中的宏。

  1. 文件 - >選項
  2. 信託中心 - >信任中心設置
  3. 宏設置
  4. 啓用「啓用所有宏」和「對VBA項目對象模型的信任訪問
  5. 按」 OK 「
+0

宏觀真的叫 'TestExcel_copy.xlsmTestMacro'(而不僅僅是 'TestMacro'?) – griFlo

回答

2

ü需要您的宏調用改爲

Variant result = Dispatch.call(excel, "Run", new Variant("\'"+file.getName()+"\'"+ macroName)); 

因爲Excel內部文件的名稱是引號之間,因此它沒有「\'」

0

無需添加file.getname()沒有找到你的宏的名稱,而調用宏。只有macroname就足夠了。

使用

Variant result = Dispatch.call(excel, "Run", new Variant(macroName)); 
0

確切的說:

Dispatch.call(excel, "Run", new Variant("\'"+file.getName()+"\'!" + macroName));