Last active
June 8, 2021 07:53
-
-
Save aspose-com-gists/1d8519df9064d918a223e1278e9f0ff7 to your computer and use it in GitHub Desktop.
Add or Modify VBA Macro in Excel using Java | https://blog.aspose.com/2021/06/08/add-modify-vba-macros-in-excel-using-java/
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 | |
// Load Excel workbook | |
Workbook workbook = new Workbook("workbook.xlsm"); | |
// Access first worksheet | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Add VBA Module | |
int idx = workbook.getVbaProject().getModules().add(worksheet); | |
// Access the VBA Module, set its name and codes | |
VbaModule 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("output.xlsm", SaveFormat.XLSM); |
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 | |
// Create workbook object from source Excel file | |
Workbook workbook = new Workbook("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("output.xlsm"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read the complete article: https://blog.aspose.com/2021/06/08/add-modify-vba-macros-in-excel-using-java/