使用 Aspose.Cells 添加 VBA 模块和代码
Contents
[
Hide
]
Aspose.Cells 允许您使用 Aspose.Cells 添加新的 VBA 模块和宏代码。请使用Workbook.getVbaProject().getModules().add() 方法在工作簿中添加新的 VBA 模块
使用 Aspose.Cells 添加 VBA 模块和代码
以下示例代码创建一个新工作簿并添加一个新的 VBA 模块和宏代码,并以 XLSM 格式保存输出。一次,您将在 Microsoft Excel 中打开输出 XLSM 文件并单击开发人员 > Visual Basic菜单命令,您将看到一个名为“TestModule”的模块,在其中,您将看到以下宏代码。
Sub ShowMessage()
MsgBox "Welcome to Aspose!"
End Sub
示例代码
下面是使用 VBA 模块和宏代码生成输出 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 | |
// 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); | |