3

I'm using win32com.client from the pywin32 module to accept all tracked changes in a word document (Python 3.6.4 on Windows 10 64 bit).

Specifically the code I'm using is the following:

import win32com.client as win32


word = win32.gencache.EnsureDispatch("Word.Application")
word.Visible = False
doc = word.Documents.Open(PATH TO WORD FILE)
doc.Activate()
word.ActiveDocument.TrackRevisions = False  # Maybe not need this

try:
    word.WordBasic.AcceptAllChangesInDoc()
except TypeError:
    pass

word.ActiveDocument.Save()
doc.Close(False)
word.Application.Quit()

I have two questions.

1.) Is there a better way to accept all changes rather than using the try-except block? Using this method produces a TypeError so a try-except block is required to finish the program.

2.) Do you know how you can delete comments left from users?

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
probat
  • 1,422
  • 3
  • 17
  • 33

1 Answers1

7

Here is a code working with Python 2.7 (I assume it works with Python 3.6.4 as well - I'm not familiar yet with the change between 2.X and 3.X)

#!/usr/bin/env python3

import win32com.client as win32

path_file_name = "YourPath\ToYour\doc.docx"
word = win32.gencache.EnsureDispatch("Word.Application")
word.Visible = False
doc = word.Documents.Open(path_file_name )
doc.Activate()
word.ActiveDocument.TrackRevisions = False  # Maybe not need this (not really but why not)

# Accept all revisions
word.ActiveDocument.Revisions.AcceptAll()
# Delete all comments
if word.ActiveDocument.Comments.Count >= 1:
    word.ActiveDocument.DeleteAllComments()

word.ActiveDocument.Save()
doc.Close(False)
word.Application.Quit()

Let me know if it works out for you.

CristiFati
  • 38,250
  • 9
  • 50
  • 87
Ben.T
  • 29,160
  • 6
  • 32
  • 54
  • it worked! You are awesome. I'm not good at decoding the win32com documentation on activestate. Thank you greatly for taking the time to help out. – probat Mar 09 '18 at 03:55
  • I usually look for the command in VBA [here](https://msdn.microsoft.com/vba/office-vba-reference) and try to transpose it to python. After some tries and errors, you understand the difference or know how to change to make it work. – Ben.T Mar 09 '18 at 18:05
  • @Ben.T, I have a problem(https://stackoverflow.com/questions/65980692/how-to-call-method-changefileopendirectory-vba-using-python). Can you please help me? – Thuấn Đào Minh Jan 31 '21 at 15:20
  • Hi @ThuấnĐàoMinh, unfortunately, I haven't work with this library in a long time now and I don't have the right set up anymore, I'm not sure I can be really helpful – Ben.T Jan 31 '21 at 15:26