Modifying VBA or Macro Code using Aspose.Cells
You can modify VBA or Macro Code using Aspose.Cells. Aspose.Cells has added the following classes to read and modify the VBA project in the Excel file.
- VbaProject
- VbaModuleCollection
- VbaModule
This article will show you how to change the VBA or Macro Code inside the source Excel file using Aspose.Cells.
Example
The following sample code loads the source Excel file which has a following VBA or Macro code inside it
Sub Button1_Click()
MsgBox "This is test message."
End Sub
After the execution of Aspose.Cells sample code, the VBA or Macro code will be modified like this
Sub Button1_Click()
MsgBox "This is Aspose.Cells message."
End Sub
You can download the source Excel file and the output Excel file from the given links.
// 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"); |