管理Excel宏启用的工作簿的VBA代码。
Contents
[
Hide
]
在C#中添加VBA模块
Aspose.Cells允许您使用Aspose.Cells添加新的VBA模块和宏代码。请使用Workbook.VbaProject.Modules.Add()方法在工作簿内添加新的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-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create new workbook | |
Workbook workbook = new Workbook(); | |
// Access first worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Add VBA Module | |
int idx = workbook.VbaProject.Modules.Add(worksheet); | |
// Access the VBA Module, set its name and codes | |
Aspose.Cells.Vba.VbaModule module = workbook.VbaProject.Modules[idx]; | |
module.Name = "TestModule"; | |
module.Codes = "Sub ShowMessage()" + "\r\n" + | |
" MsgBox \"Welcome to Aspose!\"" + "\r\n" + | |
"End Sub"; | |
// Save the workbook | |
workbook.Save(dataDir + "output_out.xlsm", SaveFormat.Xlsm); |
在C#中修改VBA或宏代码
您可以使用Aspose.Cells修改VBA或宏代码。Aspose.Cells已添加以下名称空间和类来读取和修改Excel文件中的VBA项目。
- Aspose.Cells.Vba
- VbaProject
- VbaModuleCollection
- VbaModule
本文将向您展示如何使用Aspose.Cells更改源Excel文件中的VBA或宏代码。
以下示例代码加载带有以下VBA或宏代码的源Excel文件
Sub Button1_Click()
MsgBox "This is test message."
End Sub
执行Aspose.Cells示例代码后,VBA或宏代码将被修改如下
Sub Button1_Click()
MsgBox "This is Aspose.Cells message."
End Sub
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-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create workbook object from source Excel file | |
Workbook workbook = new Workbook(dataDir + "sample.xlsm"); | |
// Change the VBA Module Code | |
foreach (VbaModule module in workbook.VbaProject.Modules) | |
{ | |
string code = module.Codes; | |
// 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.Codes = code; | |
} | |
} | |
// Save the output Excel file | |
workbook.Save(dataDir + "output_out.xlsm"); |