DEV Community

carlwils
carlwils

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.

<repositories>
   <repository>
      <id>com.e-iceblue</id>
      <name>e-iceblue</name>
      <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
   </repository>
</repositories>
<dependencies>
   <dependency>
      <groupId>e-iceblue</groupId>
      <artifactId>spire.doc.free</artifactId>
      <version>5.1.0</version>
   </dependency>
</dependencies>
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();
        doc.loadFromFile("macros.docm");

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

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

    }
}

Enter fullscreen mode Exit fullscreen mode

RemoveMacro

Top comments (0)