[python-win32] Controlling Excel via COM: errors with conditional formatting

Tim Roberts timr at probo.com
Wed Sep 24 19:35:09 CEST 2008


kurt munson wrote:
> I  have written a Python program to control MS Excel via
> win32com.client. This allows me to create and control an Excel
> spreadsheet.
>
> I want to use Excel's conditional formatting to color certain cells,
> but I can't get it to work.
>
> Here's the code I use:
>
>     |import win32com.client
>     xl= win32com.client.Dispatch("Excel.Application")
>     ....
>     ....
>     ....
>     channamesSheet.Cells(6,3).FormatConditions.Add() Type:=1,
>     Operator:=4, Formula1:="=C5"
>     channamesSheet.Cells(6,3).FormatConditions(1).Interior.ColorIndex = 3|
>
> I got this code from a record and replay macro in Excel, then swapped
> out the xl constants for numeric values (1 and 4).
>
> This gives me a syntax error when running.
>
> I have tried both .Add and .Add(), since sometimes these () are necessary.
>
> What am I doing wrong?

What you are doing wrong is writing Python scripts as if it were Visual
Basic.  Solomon gave you the code, but you need to understand that
Python and Visual Basic are different languages.  When Excel records a
macro, it records it in Visual Basic.  The "Arg:=Value" syntax is a
Visual Basic syntax.  The "sometimes these () are necessary" comment
comes from Visual Basic.

By the way, after you use Dispatch, all of Excel's "xl" constants are
available to you.
    import win32com.client
    xl = win32com.client.dispatch( "Excel.Application" )
    print win32com.clients.constants.xlLandscape

-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the python-win32 mailing list