Last active
August 23, 2022 12:55
-
-
Save aspose-com-gists/472b011882a191b709e23e7780c2b575 to your computer and use it in GitHub Desktop.
Manipulate VBA Macros in Excel using C#
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 | |
// 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); |
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 | |
// 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); | |
} |
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 | |
// 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