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

在 C# 添加一个 VBA 模块

以下示例代码创建一个新工作簿并添加一个新的 VBA 模块和宏代码,并以 XLSM 格式保存输出。一次,您将在 Microsoft Excel 中打开输出 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或宏

以下示例代码加载源 Excel 文件,其中包含以下 VBA 或宏代码

 Sub Button1_Click()

    MsgBox "This is test message."

End Sub

Aspose.Cells示例代码执行后,VBA或Macro代码会修改成这样

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

推进主题