管理Excel宏启用的工作簿的VBA代码。

在C#中添加VBA模块

以下示例代码创建一个新工作簿,并添加一个新的VBA模块和宏代码,将输出保存为XLSM格式。一旦您打开输出的XLSM文件并单击“开发人员> Visual Basic”菜单命令,您将看到一个名为“TestModule”的模块,并在其中看到以下宏代码。

 Sub ShowMessage()

    MsgBox "Welcome to Aspose!"

End Sub

以下是生成带有VBA模块和宏代码的输出XLSM文件的示例代码。

// 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或宏代码

以下示例代码加载带有以下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

您可以从以下链接下载源Excel文件输出Excel文件

// 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");

高级主题