使用 Aspose.Cells 添加 VBA 模块和代码
Contents
[
Hide
]
Aspose.Cells 允许您使用 Aspose.Cells 添加新的 VBA 模块和宏代码。请使用 Workbook.getVbaProject().getModules().add() 方法向工作簿中添加新的 VBA 模块。
使用 Aspose.Cells 添加 VBA 模块和代码
以下示例代码创建一个新工作簿,并添加一个新的VBA模块和宏代码,将输出保存为XLSM格式。一旦您打开输出的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); | |