How to: Add Formulas to Cells
- 2 minutes to read
To add a formula to a cell, use the CellRange.Formula property of the Cell object. Assign the required formula to this property as a string starting with the equals sign (“=”).
This example demonstrates how to create a simple formula using constants and calculation operators, and add this formula to a cell. Constants are values that are not calculated (e.g., date values, numbers, text strings). Operators specify what calculations should be performed on a formula’s elements.
// Use constants and calculation operators in a formula.
workbook.Worksheets[0].Cells["B2"].Formula = "= (1+5)*6";
For more information on formulas, refer to the Spreadsheet Formulas section, and review the following examples.
- How to: Use Cell and Worksheet References in Formulas
- How to: Use Names in Formulas
- How to: Use Functions and Nested Functions in Formulas
When you set the CellRange.Formula property for the cell range, each cell in this range will contain the specified formula with adjusted cell references (all relative cell references included in the formula will automatically be changed). This approach allows you to avoid the need to copy the same formula to multiple cells and manually update cell references. Refer to the How to: Create Shared Formulas example for more information.
To perform calculations with arrays of cells, use array formulas. To create an array formula, call the CellRange.ArrayFormula method. Refer to the How to: Create Array Formulas example for more information.