Edit Macro in Word using C#

This article guides on how to edit macro in Word using C#. It has details to set the IDE, a list of instructions, and a sample code to modify macro using C#. You will also get details to access the existing modules in a Word file and modify the contents as per the requirements.

Steps to Edit Macros in Word using C#

  1. Set the IDE to use Aspose.Words for .NET to update Word file macro
  2. Load the macro-enabled Word file into the Document class object
  3. Access the VbaProject object of the loaded Word file
  4. Create a string and define source code for the modified macro
  5. Access the collection of the modules in the VbaProject
  6. Select the target module and set the SourceCode property to the modified macro code
  7. Save the loaded document with the updated macro

These steps summarize how to change macro using C# in a DOCM Word file. Import all the necessary modules and namespaces, load the source DOCM Word file into the Document object, access the VbaProject module, define the updated macro script in a string variable, and access the collection of modules in the VbaProject module. Set the new script in the SourceCode property of the target module and save the DOCM file on the disk with the updated macro.

Code to Update Macro using C#

This code demonstrates how to edit a macro using C#. The VbaProject exposes Name, Modules (collection), References (collection), CodePage (int), and read-only flags IsProtected and IsSigned. Similarly, the VbaModule provides access to three key properties: Name (module name), SourceCode (VBA code text), and Type (procedural, document, class, or designer module).

This tutorial has taught us the process of changing macros in a Word file. To create a new macro in a Word file, refer to the article on Create a macro in Word using C#.

 English