管理包含宏的 Excel 工作簿的 VBA 代码
在 Node.js 中添加 VBA 模块
以下示例代码创建一个新工作簿,添加一个 VBA 模块和宏代码,并将输出保存为 XLSM 格式。一旦你用 Microsoft Excel 打开输出的 XLSM 文件并点击 开发者 > 视觉 Basic 菜单命令,你将看到名为 “TestModule” 的模块,里面包含以下宏代码。
Sub ShowMessage() {
MsgBox "Welcome to Aspose!"
}
以下是生成带有 VBA 模块和宏代码的输出 XLSM 文件的示例代码。
const path = require("path");
const AsposeCells = require("aspose.cells.node");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Create new workbook
const workbook = new AsposeCells.Workbook();
// Access first worksheet
const worksheet = workbook.getWorksheets().get(0);
// Add VBA Module
const idx = workbook.getVbaProject().getModules().add(worksheet);
// Access the VBA Module, set its name and codes
const module = workbook.getVbaProject().getModules().get(idx);
module.setName("TestModule");
module.setCodes("Sub ShowMessage()" + "\r\n" +
" MsgBox \"Welcome to Aspose!\"" + "\r\n" +
"End Sub");
// Save the workbook
workbook.save(path.join(dataDir, "output_out.xlsm"), AsposeCells.SaveFormat.Xlsm);
在 Node.js 中修改 VBA 或宏
你可以使用Aspose.Cells for Node.js via C++修改VBA或宏代码。Aspose.Cells已添加以下模块和类来读取和修改Excel文件中的VBA项目。
- Aspose.Cells.Vba
- VbaProject
- VbaModuleCollection
- VbaModule
本文将向您展示如何使用Aspose.Cells更改源Excel文件中的VBA或宏代码。
以下示例代码加载包含 VBA 或宏代码的源 Excel 文件
Sub Button1_Click() {
MsgBox "This is test message."
}
执行Aspose.Cells示例代码后,VBA或宏代码将被修改如下
Sub Button1_Click() {
MsgBox "This is Aspose.Cells message."
}
const path = require("path");
const AsposeCells = require("aspose.cells.node");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Create workbook object from source Excel file
const workbook = new AsposeCells.Workbook(path.join(dataDir, "sample.xlsm"));
// Change the VBA Module Code
const modules = workbook.getVbaProject().getModules();
const moduleCount = modules.getCount();
for (let i = 0; i < moduleCount; i++) {
const module = modules.get(i);
const code = module.getCodes();
if (code.includes("This is test message."))
{
code = code.replace("This is test message.", "This is Aspose.Cells message.");
module.setCodes(code);
}
}
// Save the output Excel file
workbook.save(path.join(dataDir, "output_out.xlsm"));