使用 Aspose.Cells 修改 VBA 或宏代码
Contents
[
Hide
]
您可以使用Aspose.Cells修改VBA或宏代码。Aspose.Cells添加了以下类来读取和修改Excel文件中的VBA项目。
- Vba项目
- Vba模块集合
- Vba模块
本文将向您展示如何使用 Aspose.Cells 更改源 Excel 文件中的 VBA 或宏代码。
例子
以下示例代码加载源 Excel 文件,其中包含以下 VBA 或宏代码
Sub Button1_Click()
MsgBox "This is test message."
End Sub
Aspose.Cells示例代码执行后,VBA或Macro代码会修改成这样
Sub Button1_Click()
MsgBox "This is Aspose.Cells message."
End Sub
您可以下载源Excel文件和输出Excel文件从给定的链接。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
String dataDir = Utils.getDataDir(ModifyVBAorMacroCode.class); | |
// Create workbook object from source Excel file | |
Workbook workbook = new Workbook(dataDir + "sample.xlsm"); | |
// Change the VBA Module Code | |
VbaModuleCollection modules = workbook.getVbaProject().getModules(); | |
for (int i = 0; i < modules.getCount(); i++) { | |
VbaModule module = modules.get(i); | |
String code = module.getCodes(); | |
// Replace the original message with the modified message | |
if (code.contains("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(dataDir + "output.xlsm"); |