7
Excel.Worksheet.Cells[row,col] = "=Formula / reference" 

虽然在上面的 Excel 中更新公式/参考并在数据表中显示结果,但在下面的代码中,使用Range.set_Value(..)数据表时根本没有更新

string[,] myFormulas = new string[nrRows, nrColumns];
...
myFormulas [x,y] = e.g. "=SUM(D1:D" + rowNr + ")";
myFormulas [x,y+1] = e.g. "=Table1!A1";
...
Range.set_Value(Missing.Value, myFormulas)

它仅将公式显示为字符串,例如=Table1!A1.

我不能让它更新。既不是 with CalucalteAll(),也不是 with RefreshAll(),也不是 with anyhing 。任何建议如何在数据表中实现更新?

编辑:您可以使用单个语句设置整个数组Range.set_Value(Missing.Value, myFormulas)。我的问题是如何让 excel 评估这个数组中的公式(而不是将它们视为简单的字符串,或者将 Excel 重新计算的单元格一一设置。)?

4

3 回答 3

13

我发现 rangeVariable.Formula = rangeVariable.Value 会将“公式作为文本”转换为真正的 Excel 公式,这是针对该范围内的所有单元格完成的。

Worksheet sheetOne = ...
int numberOfRows = 5000;

// Make a massive range on sheet 1, then use cell assignment by array for fastness
Range range = sheetOne.Range["A1"];
string[,] links = new string[numberOfRows+1, 1];
range = range.Resize[numberOfRows+1, 1];

for (int count = 0; count < numberOfRows; count++)
{
    // Build the =HYPERLINK formula to set as text in each cell
    string worksheet = "Sheet2";
    string cellRef = string.Format("A{0}", count + 1);
    string formula = string.Format("=HYPERLINK(\"#{0}!{1}\", \"{2}\")", worksheet, cellRef, string.Format("Hyperlink number {0}", count));

    links[count, 0] = formula;
}

//range.set_Item(Type.Missing, Type.Missing, links);
range.set_Value(Type.Missing, links) // thanks HeinrichStack
range.Formula = range.Value; //<--- Boom baby, all 'formula as text' turns into bona fide excel formula

希望这可以帮助

于 2013-05-29T16:52:54.197 回答
1

I dont think that there is any way to set the Formula value for any given cell, except by deliberately setting the Formula property for it, one cell at a time.

Check out the properties and examples here

so I think what you need to do is something more like this:

Worksheet.Cells[x,y].Formula = "=SUM(D1:D" + rowNr + ")";
Worksheet.Cells[x,y+1].Formula = "=Table1!A1";
于 2013-05-06T14:17:38.093 回答
1

我不久前刚刚遇到了这个问题,并且几乎整天都在寻找解决方案,但没有运气。

在尝试解决另一个与单元格数据类型有关的问题时,我终于找到了一个解决方案,您应该将二维数组设置为“对象”类型而不是“字符串”类型。在我看来,问题的原因是公式属性(也是 Value、Value2)自动写入数据取决于代码中的数据类型。代码应该是这样的:

Worksheet sampleSheet = ...;
object[,] dataArr = new object[rowNum,colNum];
for (int i = 0; i < rowNum; i+=1) {
  for (int j = 0; j < colNum; j+=1) {
    dataArr[i,j] = "=SUM(..<something here>..)";
  }  
}
sampleSheet.Range[....].Formula = dataArr;

希望这有帮助!

于 2017-03-01T07:28:59.897 回答