Search code examples
pythonms-wordbookmarkswin32com

How to insert bookmark in Word using Python (win32com)?


I am using win32com, how can I insert a bookmark with an existing text in the Word Document ?


Solution

  • Here you go:

    import win32com.client
    wordApp = win32com.client.Dispatch('Word.Application') # alternately DispatchEx
    wordApp.visible = True                                 # alternately False or leave out
    wordDoc = wordApp.Documents.Open('c:/my_word_doc.docx')
    myRange = wordDoc.Content
    myRange.Find.Execute(FindText='peanuts')
    myRange.Bookmarks.Add(Name='X')
    wordDoc.SaveAs('c:/my_word_doc.docx')
    wordDoc.Close()
    wordApp.Quit()
    

    If you don't want Word to be visible during this process use win32com.client.DispatchEx and don't set wordApp.visible to True.