Search code examples
pythonexcelwinapiwin32com

win32 excel copy except function


I use win32com in python for excel control and facing a little problem.

I want to copy my Excel Cell (1,1) i.e.B2 to "A1"

Excel Worksheet

Below is my code

Sheet.Range(Sheet.Cells(1,1), Sheet.Cells(LastRow, Lastcol)).copy(Sheet1.Range("A1"))

It works OK, but it copies the formula not the formula value (result). ( I want "0" not a "=SUM(C1,C2)" )

Please guide, how should I change my code to get desired results?


Solution

  • It might be happening due to incorrect format of the destination cell. Hence, your code needs to be changed to below. I suggest that replace your exisiting given line with below:

    'Change the format of cell to General as Text fields do not evaluate the formula
    Sheet.Range(Sheet.Cells(1,1), Sheet.Cells(LastRow, Lastcol)).NumberFormat = "General"
    
    'Copy the formula and assign it as formula (rather than copying it)
    Sheet.Range(Sheet.Cells(1,1), Sheet.Cells(LastRow, Lastcol)).Formula  = Sheet1.Range("A1").Formula
    

    Hope it helps !