Question

My C# code manipulates Excel Ranges using Microsoft.Office.Interop.Excel library. I need to assign a Formula Array to a selected Range. I've tried a variety of methods recommended online, including Microsoft recommendations, but so far was unable to make it work properly.

I observe 2 issues:

Issue 1. Assignment looks fine on surface: it does not fail, cell objects in the range show .ArrayFormula property assigned, on the spreadsheet formula in every cell appears in curly brackets. However, the Formula Array is actually disjointed: each cell in the range can be changed separately, which normal Formula Array would not permit. It behaves as if every cell had its own, single-cell Formula Array, independent from others. Regardless of my best efforts, this is ALWAYS the case. Is there actually a properly working solution for this issue?

Issue 2. My Array Formula contains a reference to another Range (Range A), which I need to refer to in R1C1 style. I need Array Formula in every cell in the target Range point to the same Range A. Somehow I always end up with every cell in target Range having its own version of the formula, referring to shifted "Range A" area. How do I make the reference stay in place, regardless of a cell?

N.B. You may assume that Issue 2 is causing Issue 1, but this is not the case: for example, when array formula is simple, like "=SIN(1)", the Issue 1 still occurs.

I would really appreciate any WORKING suggestions. Thanks a lot in advance.

Was it helpful?

Solution

No one seemed interested, however I found a solution and will answer to my own question.

Apparently, assignment of an Excel Array Formula within C# code works only if the formula is in A1 style, not in R1C1 style. In my case, I was starting with a R1C1-style formula, so it required conversion to A1 style. This is achieved by assigning the original R1C1-style formula to the top left cell of the target range:

topLeftCell.Formula = myR1C1Formula;  
// topLeftCell.FormulaR1C1 = myR1C1Formula also works

Assignment to that particular cell will ensure that A1-style formula contains correct references. Get back the converted formula as a string:

string formulaA1 = topLeftCell.Formula;

Get reference to the whole target range by rezising the top left cell:

Excel.Range newArrayRange = topLeftCell.Resize[height, width];

Resize operation must precede the following assignment. Finally, assign the A1-style formula to the FormulaArray property of the whole target range:

newArrayRange.FormulaArray = formulaA1; 

This works perfectly without issues or side-effects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top