管理启用 Excel 宏的工作簿的 VBA 代码。
Contents
[
Hide
]
在 C# 添加一个 VBA 模块
Aspose.Cells 允许您使用 Aspose.Cells 添加新的 VBA 模块和宏代码。请使用工作簿.VbaProject.Modules.Add()在工作簿中添加新的 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-.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
- Vba项目
- Vba模块集合
- Vba模块
本文将向您展示如何使用 Aspose.Cells 更改源 Excel 文件中的 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文件从给定的链接。
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"); |