We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

How to update row formula fields

I have a template where there are row based formulas i.e. c2+d2 and g2 - e2
When I’m cloning and inserting new rows, how would I deal with the formulas like that? (because the clone logic is keeping the formula as is, and I need to update it to c[insert current row index here] + d[insert current row index here], for each row, and each row’s index may change as the document is built.
attached is a project for an example. if you look in the test.dot template, there are ‘row based’ formulas in 2 of the cells.
if you look in result.docx, they are clone, but the index part of the formula doesn’t update based on current row, and I need them to be updated.

fields.zip (38.6 KB)


You can update the index values inside formula field by using the following code:

Document doc = new Document(MyDir + @"fields\result.docx");
Table table = doc.FirstSection.Body.Tables[0];

for (int i = 0; i < table.Rows.Count - 1; i++)
    Row row = table.Rows[i];

    foreach (Field field in row.Range.Fields)
        if (field.Type == FieldType.FieldFormula)
            FieldFormula formula = (FieldFormula)field;

            string fieldCode = formula.GetFieldCode();
            string numericFormat = formula.Format.NumericFormat;
            string targetString = fieldCode.Replace(numericFormat, "");
            string replaced = Regex.Replace(targetString, "[0-9]", "" + (i + 1));                       

            Node currentNode = formula.Start.NextSibling;
            bool isRemoving = true;
            while (currentNode != null && isRemoving)
                if (currentNode.NodeType == NodeType.FieldSeparator)
                    isRemoving = false;

                Node nextNode = currentNode.NextPreOrder(currentNode.Document);
                currentNode = nextNode;

            Run run = (Run)formula.Start.NextSibling;
            run.Text = replaced + numericFormat;



doc.Save(MyDir + @"fields\18.5.docx");

thank you, that fixed it

spoke to soon
project attached.
I’m getting an access violation in the call to formula.update
fields.zip (34.4 KB)


Please spare us some time for the investigation of this scenario. We will update you the earliest possible.


I have commented the following method call from the end of your “testMerge” method


and generated result.docx (see result.zip (9.2 KB))

After that for this result.docx, I executed the exactly same code from my previous post and managed to produce correct final output (see 18.5.zip (9.2 KB)).