RSS category feeds

RSS site feeds


Events in Microsoft Word and Excel PDF Print E-mail
I think this must be an example from Marc Hammond. It shows how to connect to events in Microsoft Word and Excel:
# OfficeEvents - test/demonstrate events with Word and Excel.
from win32com.client import DispatchWithEvents, Dispatch
import msvcrt, pythoncom
import time, sys
import types
import threading
stopEvent = threading.Event()
def TestExcel():
    class ExcelEvents:
        def OnNewWorkbook(self, wb):
            if type(wb) != types.InstanceType:
                raise RuntimeError, "The transformer doesnt appear to have translated this for us!"
            self.seen_events["OnNewWorkbook"] = None
        def OnWindowActivate(self, wb, wn):
            if type(wb) != types.InstanceType or type(wn) != types.InstanceType:
                raise RuntimeError, "The transformer doesnt appear to have translated this for us!"
            self.seen_events["OnWindowActivate"] = None
        def OnWindowDeactivate(self, wb, wn):
            self.seen_events["OnWindowDeactivate"] = None
        def OnSheetDeactivate(self, sh):
            self.seen_events["OnSheetDeactivate"] = None
        def OnSheetBeforeDoubleClick(self, Sh, Target, Cancel):
            if Target.Column % 2 == 0:
                print "You can double-click there..."
                print "You can not double-click there..."
            # This function is a void, so the result ends up in
            # the only ByRef - Cancel.
                return 1
    class WorkbookEvents:
        def OnActivate(self):
            print "workbook OnActivate"
        def OnBeforeRightClick(self, Target, Cancel):
            print "It's a Worksheet Event"
    e = DispatchWithEvents("Excel.Application", ExcelEvents)
    e.seen_events = {}
    book = e.Workbooks.Add()
    book = DispatchWithEvents(book, WorkbookEvents)
    print "Have book", book
#    sheet = e.Worksheets(1)
#    sheet = DispatchWithEvents(sheet, WorksheetEvents)
    print "Double-click in a few of the Excel cells..."
    print "Press any key when finished with Excel, or wait 10 seconds..."
    if not _WaitForFinish(e, 10):
    if not _CheckSeenEvents(e, ["OnNewWorkbook", "OnWindowActivate"]):
def TestWord():
    class WordEvents:
        def OnDocumentChange(self):
            self.seen_events["OnDocumentChange"] = None
        def OnWindowActivate(self, doc, wn):
            self.seen_events["OnWindowActivate"] = None
        def OnQuit(self):
            self.seen_events["OnQuit"] = None
    w = DispatchWithEvents("Word.Application", WordEvents)
    w.seen_events = {}
    w.Visible = 1
    print "Press any key when finished with Word, or wait 10 seconds..."
    if not _WaitForFinish(w, 10):
    if not _CheckSeenEvents(w, ["OnDocumentChange", "OnWindowActivate"]):
def _WaitForFinish(ob, timeout):
    end = time.time() + timeout
    while 1:
        if msvcrt.kbhit():
        if stopEvent.isSet():
            if not ob.Visible:
                # Gone invisible - we need to pretend we timed
                # out, so the app is quit.
                return 0
        except pythoncom.com_error:
            # Excel is busy (eg, editing the cell) - ignore
        if time.time() > end:
            return 0
    return 1
def _CheckSeenEvents(o, events):
    rc = 1
    for e in events:
        if not o.seen_events.has_key(e):
            print "ERROR: Expected event did not trigger", e
            rc = 0
    return rc
def test():
    import sys
    if "noword" not in sys.argv[1:]:
    if "noexcel" not in sys.argv[1:]:
    print "Word and Excel event tests passed."
if __name__=='__main__':
Last Updated ( Saturday, 06 November 2010 )
< Prev   Next >




  • hey how can we clear history of a single skype group ? any idea? More...
  • Dear Brent I'm trying to get the points coordinate in a PYTHON/CATIA macro but I... More...
  • Hi Brent, I'm trying to create a macro for create the best fitting circle given... More...
  • I have run your code on my own machine, but I just got the last paragraph of the... More...
  • Hello Gabriel, It seem that the linked site moved to (... More...

Login Form

Lost Password?

My prefered Python IDE

My prefered Python editor is Pyscripter from MMExperts. It is not only an editor. Pyscripter is a full Python IDE including (remote) debugging, a class browser, and all other nice helpers which a full featured IDE needs.

Do you have a script for me ?

Do you have an interesting Python script which does some really cool thing on Windows ? Please post them to this site. It`s very simple - simply copy&paste it to this form. No login is requiered.

Hint: For syntax highlighting and correct Python intendation place your code between html tags <pre> and </pre>.

My prefered web framework

My prefered web framework for developing web applications is Django. Django calls itself The web framework for perfectionists with deadlines. It is a really fast, scalable and (thanks Python) the sexiest web framework of the world.