使用 Aspose.Cells 修改 VBA 或宏代码
Contents
[
Hide
]
您可以使用 Aspose.Cells 修改 VBA 或宏代码。Aspose.Cells 已添加以下类以读取和修改 Excel 文件中的 VBA 项目。
- VbaProject
- VbaModuleCollection
- VbaModule
本文将向您展示如何使用Aspose.Cells更改源Excel文件中的VBA或宏代码。
示例
以下示例代码加载带有以下VBA或宏代码的源Excel文件
Sub Button1_Click()
MsgBox "This is test message."
End Sub
执行Aspose.Cells示例代码后,VBA或宏代码将被修改如下
Sub Button1_Click()
MsgBox "This is Aspose.Cells message."
End Sub
您可以从以下链接下载源 Excel 文件和输出 Excel 文件。
This file contains 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"); |