So here's what I am going through. I am using the Excel dll with c# in order to go inside a big and nasty excel sheet so that others don't have to.
We have a formula in one cell that is rather large and we don't want to copy it to every row because of this. This formula uses multiple values on the row that it is placed on. If it is on row 1, it uses lots of cells from that row.
When one copies this formula normally in excel, the new ranges of the cells are modified to reflect the new starting position.
The problem is that when I copy the formula like this, it still gives me all of the values that have to do with the first row instead of the row where I pasted it.....Here is my code:
sheet.Cells[77][row].Formula = sheet.Cells[77][1].Formula;
Can somebody let me know how to make the formula actually apply to the new row instead of row 1?
Hi guys m posting this because this code is used to copy the formula behind a cell in Excel:
This will probably work, as it works from VBA... in most cases.
This would work because FormulaR1C1(not a very informative link) uses R1C1 notation which describes the referenced cells location in relation to the current cell instead of saying which cells to use. This means the actual references are dependent on the cell with the formula. When you just use
Formula
, you're copying the string of theFormula
exactly including the hard coded cell references.You could use
Application.ConvertFormula
So, let's say my Cell = Cells77 has a formula that says
=Sum(B77,C77)
(Cells from the same row).if want to copy it to a cell right below it, you would do something like:
Full console app that works (You need to modify cells though).
You can modify third and forth parameter of
ConvertFormula
method to your liking. Read more about the method here: ConvertFormula.If you want to stretch formula accross multiple rows, you can try to use range.AutoFill()