[Tutor] Planning to write Python scripts and programs (migrating
a Basic macro)
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Thu, 17 Jan 2002 19:25:25 -0800 (PST)
On Wed, 16 Jan 2002, McCarney, James Alexander wrote:
> I have a Word (Basic) macro that I run against images in docs that I
> create to resize them. I wonder if I could either rewrite it totally
> in Py or have Py open the document file, execute the macro, save the
> file, and quit.
Hi James,
Yes, it's possible to do this. You may want to look at the book "Python
and Win32 Programming", by Mark Hammond:
http://www.oreilly.com/catalog/pythonwin32/
I don't have the book with me, but I think the book does cover examples of
making Word dance around with Python. If you're a Windows user, and you
want to use Python to fiddle around with Windows itself, the book is a
must buy.
> The Basic code is this (shield your eyes or snip it out now, cos it's
> not Py!!!)
Don't worry about it; I think we can handle it. *grin*
> Sub ReduceTo50()
> '
> ' ReduceTo50 Macro
> ' Macro created 09/12/01 by James Alexander McCarney
> '
> Dim lngX As Long
> On Error Resume Next 'Important or the code may puke
>
> For lngX = 1 To ActiveDocument.InlineShapes.Count
> ActiveDocument.InlineShapes(lngX).Select
> If (ActiveDocument.InlineShapes(lngX).Type = wdInlineShapeLinkedPicture
> Or ActiveDocument.InlineShapes(lngX).Type = wdInlineShapePicture) Then
> Selection.InlineShapes(1).ScaleHeight = 40 'Set the height to
> whatever you want 50, 40, 30 (for smaller pix)
> Selection.InlineShapes(1).ScaleWidth = 40 'Set the height to
> whatever you want 50, 40, 30 (for smaller pix)
>
> End If
>
> Next lngX
>
> End Sub
Hey, that didn't look too bad at all. Wow, BASIC has changed. *grin*
I think this function should translate pretty well to Python, but I don't
know well enought the kind of objects we can fool around with. Oh well,
I'll try guessing. Here's a very buggy translation --- I'm positive that
it won't work --- but it might help you get started:
###
def ReduceTo50():
"""
ReduceTo50 Macro
Macro created 09/12/01 by James Alexander McCarney
"""
for i in range(1, ActiveDocument.InlineShapes.Count):
try:
shape = ActiveDocument.InlineShapes(i)
shape.Select()
if shape.Type in (wdInlineShapeLinedPicture,
wdInlineShapePicture):
selection.InlineShapes(1).ScaleHeight = 40
selection.InLineShapes(1).ScaleWidth = 40
except Exception, e:
## Do we want to pass errors silently? Maybe
## we should say something to the user to warn them.
## For now, let's just pass it.
pass
###
Since it looks like you're doing a lot of Windows specific stuff, you'll
definitely want to get in contact with the python-win32 mailing list, so
that you can also ask for their expertise too. You can find them here:
http://mail.python.org/mailman/listinfo/python-win32
Best of wishes to you. Tell us your progress on this; it sounds really
interesting!