Skip to main content
All docs
V24.2

DevExpress v24.2 Update — Your Feedback Matters

Our What's New in v24.2 webpage includes product-specific surveys. Your response to our survey questions will help us measure product satisfaction for features released in this major update and help us refine our plans for our next major release.

Take the survey Not interested

VBA Macros in Word Documents

  • 2 minutes to read

VBA (Visual Basic for Applications) macros are scripts written in Microsoft’s Visual Basic for Applications language. These scripts can automate tasks within a document (for example, to format or insert text).

Word Processing Document API allows you to obtain and remove VBA macro project associated with a document. VBA macros are available in the following document formats:

  • DOCM
  • DOTM
  • DOC

#Obtain VBA Macro Project

The Document.VbaProject property retrieves the VBA project associated with a document. Use the VbaProject.Modules property to get a collection of macro modules. The VbaModuleCollection.Item[String] property allows you to obtain an individual VbaModule by its name.

You can get the module name and binary data. The module name starts with a VBA\ prefix. The binary data contains all macros of a module. You can parse binary data manually to retrieve an individual macro.

The following code snippet retrieves VBA modules and collects all module names to a separate list:

using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;

using (var wordProcessor = new RichEditDocumentServer())
{
    Document document = wordProcessor.Document;
    var names = new List<string>();
    if (document.VbaProject.Modules.Count > 0)
        foreach (VbaModule module in document.VbaProject.Modules)
        { names.Add(module.Name); }
}

#Remove Macro Modules

Use one of the following methods to remove VBA modules from the document:

The following code snippet removes all VBA modules:

using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;

using (var wordProcessor = new RichEditDocumentServer()) {
    // Check if the current document has macros and remove them
    Document document = wordProcessor.Document;

    if (document.VbaProject.Modules.Count > 0)
        document.VbaProject.Modules.Clear();
}