結果が定義されていないため、つまり式の結果が値はセルに何を表示しますか?
将来の再利用のために数式を保存したいので、数式を適用し、それらを辞書に保存する Recalculate メソッドを持つことができます (そして、あなたはすでにそのようなものを持っていますよね?) そして、現在の値を持つセル (数式から計算)。
おそらくこれはあなたがここですでに行っていることですが、evalResults が何であるかを理解していないため、あまり明確ではありません。とにかく、私はこのようなことを意味します:
private Dictionary<int,Dictionary<int,string>> formulas = new Dictionary<int,Dictionary<int,string>>(); // this has to be initialized according to your formulas
public void Recalculate()
{
XL.Worksheet worksheet = Globals.ThisAddIn.Application.ActiveSheet;
XL.Range range = worksheet.UsedRange;
for (int iRow = 1; iRow <= arrValue.GetLength(0); iRow++)
{
for (int iCol = 1; iCol <= arrValue.GetLength(1); iCol++)
{
range.Cells[iRow, iCol].Formula = "=" + formulas[iRow][iCol];
range.Cells[iRow, iCol].Value = range.Cells[iRow, iCol].Value;
}
}
}
数式をメモリ (辞書) ではなく Excel ワークブックに保持する場合は、数式を文字列として (つまり、'=' なしで) 格納する非表示のワークシートを作成して、数式を回避することができます。評価とパフォーマンスの問題。そのため、コードに非常によく似た SetFormulas と Recalculate メソッドがあります。
public void SetFormulas()
{
XL.Worksheet worksheet = Globals.ThisAddIn.Application.ActiveSheet;
XL.Worksheet formulasWorksheet = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets["formulas"];
XL.Range range = worksheet.UsedRange;
arrValue = (object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault);
for (int iRow = 1; iRow <= arrValue.GetLength(0); iRow++)
{
for (int iCol = 1; iCol <= arrValue.GetLength(1); iCol++)
{
if (range.Cells[iRow, iCol].Formula != null)
{
range.Cells[iRow, iCol].Formula = "=" + kvp.Value.ToString(); // assign underlying formula (kvp is keyValuePair of dictionary) to the cell
formulasWorksheet.Cells[iRow, iCol].Value = kvp.Value.ToString(); // storing the formula here
}
range.Cells[iRow, iCol].Value = evalResults[count].ToString(); // assign value to the cell
count++;
}
}
}
public void Recalculate()
{
XL.Worksheet worksheet = Globals.ThisAddIn.Application.ActiveSheet;
XL.Worksheet formulasWorksheet = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets["formulas"];
XL.Range range = worksheet.UsedRange;
arrValue = (object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault);
for (int iRow = 1; iRow <= arrValue.GetLength(0); iRow++)
{
for (int iCol = 1; iCol <= arrValue.GetLength(1); iCol++)
{
if (!string.IsNullOrEmpty(formulasWorksheet.Cells[iRow, iCol].Text))
{
range.Cells[iRow, iCol].Formula = "=" + formulasWorksheet.Cells[iRow, iCol].Text; // restoring the formula
range.Cells[iRow, iCol].Value = range.Cells[iRow, iCol].Value // replacing the formula with the value
}
}
}
}