Back to Devexpress

VBA Macros in Word Documents

officefileapi-405248-word-processing-document-api-word-processing-document-vba-macros-in-word-documents.md

latest3.5 KB
Original Source

VBA Macros in Word Documents

  • Nov 21, 2024
  • 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:

csharp
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); }
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native

Using wordProcessor = New RichEditDocumentServer()
    Dim document As Document = wordProcessor.Document
    Dim names = New List(Of String)()
    If document.VbaProject.Modules.Count > 0 Then
        For Each [module] As VbaModule In document.VbaProject.Modules
            names.Add([module].Name)
        Next [module]
    End If
End Using

Remove Macro Modules

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

The following code snippet removes all VBA modules:

csharp
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();
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native

Using wordProcessor = New RichEditDocumentServer()
    ' Check if the current document has macros and remove them
    Dim document As Document = wordProcessor.Document

    If document.VbaProject.Modules.Count > 0 Then
        document.VbaProject.Modules.Clear()
    End If
End Using