VBA to Compare Two Word Documents Automatically

VBA & macros · Updated November 3, 2026

VBA to Compare Two Word Documents Automatically

To compare two Word files with VBA, open both documents and call Word’s Application.CompareDocuments method. It creates a separate comparison document that marks the differences, leaving the two source files unchanged; the macro below shows a complete example for Word on Windows.

How Word document comparison works

Word compares an original document with a revised one and produces a third document showing detected changes. The result usually displays insertions and deletions as tracked changes, along with other differences selected in the comparison options. It is a review copy, not a merged file that silently replaces either source.

The direction matters: Word treats the first file as the original and the second as the revised version. For example, if a sentence appears in the revised file but not the original, the comparison shows it as added. Reverse the arguments and the same sentence appears as removed. The source files themselves are not edited by the comparison operation, although a macro can separately save changes to them if written to do so.

Word’s built-in command uses the same underlying comparison capability. In Microsoft 365 for Windows, the usual ribbon route is Review > Compare > Compare. The dialog lets you choose the two files and specify what Word should examine. VBA is useful when you need to repeat that process, apply consistent options, or compare a batch of known file pairs.

When VBA is useful

A macro is most helpful when comparison is a recurring task with stable inputs. A team might receive a new draft each week and compare it with a baseline, or a document administrator might need to generate marked-up copies for several known pairs. The macro can standardize options such as whether formatting changes count, and can save the result to a predictable location.

Automation does not make the comparison more authoritative. Word identifies textual and structural differences according to its comparison settings; a person still needs to decide whether each change is correct, important, or acceptable. A comparison also cannot establish which file is the legally controlling version. For high-stakes records, follow the organization’s document-control process and preserve the original files.

Prepare the files and macro

Use desktop Microsoft Word, and make copies of important documents before running an unfamiliar macro. The example opens both input files as read-only and saves the comparison as a new DOCX file. Replace the three sample paths with paths that exist on your computer, and choose an output path that does not overwrite either input.

  1. Open Word and press Alt+F11 on Windows to open the Visual Basic Editor. On a Mac, the editor shortcut can depend on the keyboard and function-key settings; use Word’s Visual Basic Editor command or the customized shortcut instead.
  2. In the editor, choose Insert > Module, then paste the macro below into the module.
  3. Change originalPath, revisedPath, and outputPath to the full paths for your files.
  4. Run CompareTwoWordDocuments from the editor, or run it through Word’s macro dialog. Save the macro in a macro-enabled document or template if you need to keep it for later.

On Windows, Word’s macro dialog can be opened with Alt+F8. On a Mac, keyboard shortcuts may differ, so use Word’s macro command from the interface. Macro availability also depends on the organization’s security settings; do not enable macros in files from untrusted sources.

Example VBA macro

Sub CompareTwoWordDocuments()
    ' Set these paths to the two source files and the new result file.
    Dim originalPath As String
    Dim revisedPath As String
    Dim outputPath As String
    Dim originalDoc As Document
    Dim revisedDoc As Document
    Dim comparisonDoc As Document

    originalPath = "C:\Documents\Draft_Original.docx"
    revisedPath = "C:\Documents\Draft_Revised.docx"
    outputPath = "C:\Documents\Draft_Comparison.docx"

    On Error GoTo ErrHandler

    ' Open source files read-only so this macro does not edit them.
    Set originalDoc = Documents.Open( _
        FileName:=originalPath, ReadOnly:=True, AddToRecentFiles:=False)
    Set revisedDoc = Documents.Open( _
        FileName:=revisedPath, ReadOnly:=True, AddToRecentFiles:=False)

    ' Create a new document containing the comparison markup.
    Set comparisonDoc = Application.CompareDocuments( _
        OriginalDocument:=originalDoc, _
        RevisedDocument:=revisedDoc, _
        Destination:=wdCompareDestinationNew, _
        Granularity:=wdGranularityWordLevel, _
        CompareFormatting:=True, _
        CompareCaseChanges:=True, _
        CompareWhitespace:=True, _
        CompareTables:=True, _
        CompareHeaders:=True, _
        CompareFootnotes:=True, _
        CompareTextboxes:=True, _
        CompareFields:=True, _
        CompareComments:=True, _
        CompareMoves:=True, _
        RevisedAuthor:="Automated comparison", _
        IgnoreAllComparisonWarnings:=False)

    ' Save the result as a standard Word DOCX file.
    comparisonDoc.SaveAs2 FileName:=outputPath, _
        FileFormat:=wdFormatXMLDocument

    MsgBox "Comparison saved to: " & outputPath, vbInformation

CleanUp:
    If Not revisedDoc Is Nothing Then
        revisedDoc.Close SaveChanges:=wdDoNotSaveChanges
    End If
    If Not originalDoc Is Nothing Then
        originalDoc.Close SaveChanges:=wdDoNotSaveChanges
    End If
    Exit Sub

ErrHandler:
    MsgBox "Comparison failed: " & Err.Description, vbExclamation
    Resume CleanUp
End Sub

Save a copy of your work before running any macro. Word macros cannot be reversed with Ctrl+Z. This particular macro opens the sources read-only, but it still creates and saves a result file, so check the output path and make sure you are comfortable with the files being processed.

What the code does and where to customize it

The two calls to Documents.Open load the source documents without allowing the macro to save edits back to them. Application.CompareDocuments then creates a comparison document because the destination is wdCompareDestinationNew. Setting Granularity to wdGranularityWordLevel asks Word to identify changes at word level rather than treating an entire sentence or paragraph as one change.

The comparison switches are all set to True in this example. This asks Word to consider formatting, case changes, whitespace, tables, headers, footnotes, text boxes, fields, comments, and moves. You can change an option to False if that category should not be included. For instance, setting CompareFormatting:=False can make a review less noisy when only wording matters. The revised author value labels the comparison markup; it does not change the author information in either source file.

SaveAs2 writes the new result as a Word DOCX file. If the output file already exists, Word may display an overwrite prompt or behave according to the current application settings. Pick a unique output name or handle existing files deliberately rather than assuming the macro will replace them without asking. After saving, the result remains open for review; the macro closes the two read-only sources.

Choose comparison settings carefully

Including every category is reasonable for a thorough review, but it can make the result harder to scan. The right settings depend on what changed and what the reviewer needs to verify.

  • Text and case: Keep case comparison enabled when capitalization matters, such as in product names, headings, or defined terms.
  • Formatting: Include it when font, emphasis, paragraph layout, or styles are part of the review. Exclude it when visual edits would distract from wording changes.
  • Whitespace: Include it to catch spacing and layout-related edits, but expect harmless spacing differences to appear.
  • Tables and text boxes: Include these when the files contain content in those structures. A reviewer should still check complex layouts visually.
  • Headers, footnotes, comments, and fields: Include relevant categories when those parts carry information that must be reviewed. A field may display a result that changes independently of ordinary typed text.

Word’s comparison is not a guarantee that two documents are identical in every practical sense. For example, a changed page break or a difference in how content flows can be important even when the words match. Review the document in context, especially if pagination, tables, section breaks, or printed layout matter.

Review the comparison document

Open the output and inspect the markup before distributing it. In Word for Windows, the Review tab contains the tracking and review controls, including the display choices for markup. Use the Reviewing Pane if you want a list of changes alongside the document, and navigate through changes rather than relying only on a quick visual scan.

Do not mistake a comparison result for an accepted revision. The new document presents differences for review; it does not decide which changes to keep. A reviewer can accept or reject changes in that result, but should preserve the source files and any required audit trail. If you need to produce a clean final document, do that only after the authorized reviewer has decided what to accept.

Word for Mac also provides document comparison, though ribbon labels and the Visual Basic Editor experience can differ by release. Look for the compare command on the Review tab and check the version’s help if the control is not in the same place. VBA support and macro security policies can vary between platforms, so verify the procedure in the target desktop Word version before relying on it in a recurring workflow.

Common problems and practical fixes

  • “File not found” or a path error: Confirm that the file names and folder paths are exact. Windows paths use backslashes, and a typo in the extension or folder name is enough to stop the macro.
  • Word cannot open a source: Check that the file is a format Word can open, that it is not already locked by another process, and that your account has permission to read it. Close a duplicate open copy if Word reports a conflict.
  • The macro is blocked: Word may disable macros because of Trust Center settings or an organization policy. Only run code you understand and trust; do not weaken security protections simply to run an unknown downloaded macro.
  • The result looks unusually busy: Formatting, whitespace, comments, and fields can add markup. Try disabling categories that are irrelevant to the review, then generate a fresh comparison.
  • Differences seem missing: Check that the intended original and revised files were passed in the correct order and that the relevant comparison options are enabled. Also inspect tables, headers, footnotes, and text boxes separately if they contain important material.
  • The output cannot be saved: Make sure the destination folder exists and is writable, and that another application is not holding the target file open. Choose a new filename if a previous comparison is already open.

For repeatable work, log which input files were compared and where the output was saved. A filename and timestamp can help identify the result, but do not rely on the filename alone as proof of document history; preserve the actual source versions according to your records process.

VBA compared with Word’s manual command

Use the built-in command when you are comparing one pair and want to choose settings interactively. It is easier for an occasional task because Word prompts you for the documents and displays the options. Use VBA when the same choices recur, the paths are predictable, or a larger automation routine must create comparisons without repeatedly opening dialogs.

Automation is less forgiving of changing file names, permissions, or document layouts. A macro can also create a misleading result if it always compares the wrong baseline. For an occasional comparison, the manual command may be safer. For a controlled repeat process, test the macro on copies, verify the output, and document the intended original/revised order.

Frequently Asked Questions

Can VBA compare two Word documents without changing them?
Yes. The example opens each source read-only and uses wdCompareDestinationNew to create a separate result. Avoid adding code that saves changes to the source documents, and check that the output path does not point to either input.

Does Word’s comparison show changes as Track Changes?
The comparison result displays detected differences as review markup in a new document. That makes it possible to inspect and act on the changes, but it does not mean the revisions have been accepted or that the result is a clean merged copy.

Can I compare only text and ignore formatting?
Yes. In the VBA call, set CompareFormatting:=False. You can also turn off other categories, such as whitespace or comments, while leaving relevant options enabled. Generate a new comparison after changing the settings.

Can I use this macro in Word for Mac?
Word for Mac has comparison features and supports VBA in desktop editions, but menus, shortcuts, file paths, and security behavior can differ. The sample uses Windows-style paths, so you must adapt them for your Mac and confirm the procedure in the Word version you use.

Can the macro compare many pairs automatically?
Yes, a larger macro can loop through files or pairs and call CompareDocuments for each one. It should check that every input exists, create distinct output names, handle errors per pair, and avoid overwriting results. Start with a small test set before automating a large folder.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.