DEV Community


Posted on


Detect and Remove Word Macros in Java

Word Macros refers to a set of programming instructions that automates tasks in Word documents. As your needs change, you may sometimes need to delete the existing macros. This article will share how to programmatically detect and remove all VBA macros in a Word document using Free Spire.Doc for Java.

Import Jar Dependency

Method 1: Download the free library and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

Enter fullscreen mode Exit fullscreen mode

Sample Code

To remove the exsting macros in a Word document, you need first load a DOCM (Word Macro-Enabled Document) file, and then use the Document.isContainMacro() and Document.clearMacros() methods to detect and remove the macros. The complete sample code is ahown as below.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RemoveMacro {
    public static void main(String[] args) throws Exception {

        //Load the Sample Word document.
        Document doc = new Document();

        //If the document contains Macros, remove them from the document.
        if (doc.isContainMacro() )

        //save to file
        doc.saveToFile("RemoveMacro.docm", FileFormat.Docm);


Enter fullscreen mode Exit fullscreen mode


Top comments (0)