Adding VBA Module and Code using Aspose.Cells
Adding VBA Module and Code using Aspose.Cells
The following sample code creates a new workbook and adds a new VBA Module and Macro Code and saves the output in the XLSM format. Once, you will open the output XLSM file in Microsoft Excel and click the Developer > Visual Basic menu commands, you will see a module named “TestModule” and inside it, you will see the following macro code.
Sub ShowMessage()
MsgBox "Welcome to Aspose!"
End Sub
Sample Code
Here is a sample code to generate the output XLSM file with VBA Module and Macro Code.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(AddVBAModuleAndCode.class); | |
// Create new workbook | |
Workbook workbook = new Workbook(); | |
// 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(dataDir + "output.xlsm", SaveFormat.XLSM); | |