Can Python COM execute a Microsoft Office macro?

Magnus Lyckå magnus at thinkware.se
Fri Feb 22 14:11:35 EST 2002


Mike Brenner wrote:

> Is there a way for the Python COM interface to execute a macro in a Microsoft Office product like Project, Word, or Excel?


Sure. I suggest that you record macros in Excel or whatever to see
what they would look like in VBA, then it's fairly simple to translate.

I opened an Excel session from Python like this:

 >>> from win32com.client import Dispatch
 >>> xl = Dispatch("Excel.Application")
 >>> xl.Visible=1
 >>> xl.Workbooks.Add()
<COMObject Add>

Then I recorded a macro in Excel -- the one I am to run. Since I don't
remember exactly how to run macros, I recorded that too. In other words,
I did "record macro" again, and while I was recording, I opened the
macro menu and clicked to run my first macro. Then I stopped the
recording of the seconed one. Finally I opened the macro editor for this
last one. It looked like this (Swedish Excel 2000).

Sub Makro2()
'
' Makro2 Makro
' Makrot inspelat 2002-02-22 av Magnus Lyckå
'

'
     Application.Run "Bok1!Makro1"
End Sub

"Application" is my variable "xl" above and Python likes (), so

 >>> xl.Run("Bok1!Makro1")

will run the macro. Easy, right?





More information about the Python-list mailing list