gpt4 book ai didi

java - 使用 Jacob 1.18 从 Java 调用宏

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:05 28 4
gpt4 key购买 nike

我在 Excel 文件中定义了一个宏,我想使用 Jacob 1.18 jar 和 dll 从 Java 程序中调用它。

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

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. 按“确定”

最佳答案

你需要改变你的宏调用

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

因为在 excel 中文件名在引号之间,所以它找不到不带“\'”的宏名

关于java - 使用 Jacob 1.18 从 Java 调用宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34766840/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com