Search code examples
pythonpython-2.7excel-2007win32com

python win32com : Change Excel formula without inputing value yourself


Is there a way to change a formula without inputing the new value yourself? Example:

Données!$EX$68:$IN$68  

should become

Données!$EY$68:$IN$68

I don't want to calculate myself EY comes after EX, since it can go up to 4 letter.

Thanks.


Solution

  • You could use R1C1 formatting to do this:

    Row1 = 1
    Column1 = 2
    Row2 = 10
    Column = 2
    
    Formula = "=sum(r%(first)sc%(second)s:r%(third)sc%(fourth)s)" % {'first':Row1, 
                                                                     'second':Column1, 
                                                                     'third':Row2, 
                                                                     'fourth':Column}
    xl.Cells(1,1).FormulaR1C1 = Formula
    

    Makes the formula: =SUM($B$1:$B$10) in cell A1. There's lots of neat things you can do with R1C1 formatting in excel, like using [] to denote offsets. Makes writing formulas from python a bit less painful. Hope this helps!