Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active August 23, 2022 12:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/472b011882a191b709e23e7780c2b575 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/472b011882a191b709e23e7780c2b575 to your computer and use it in GitHub Desktop.
Manipulate VBA Macros in Excel using C#
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// 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("output_out.xlsm", SaveFormat.Xlsm);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Create workbook object from source Excel file
Workbook workbook = new Workbook("sample.xlsm");
// Extract code from each VBA module
foreach (VbaModule module in workbook.VbaProject.Modules)
{
string code = module.Codes;
Console.Write(code);
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Create workbook object from source Excel file
Workbook workbook = new Workbook("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("output_out.xlsm");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment