c# - Excel.Worksheet.Cells[row,col] = "=Formula"与 Range.set_Value(Missing.Value, arrayFormulas)

标签 c# excel vba

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

我无法让它更新。既不使用 CalucalteAll(),也不使用 RefreshAll(),也不使用任何东西。对如何在数据表中实现更新有什么建议吗?

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

最佳答案

我发现 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

希望对你有帮助

关于c# - Excel.Worksheet.Cells[row,col] = "=Formula"与 Range.set_Value(Missing.Value, arrayFormulas),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16400302/

相关文章:

c# - 如何修复文件格式和扩展名不匹配?

vba - 加速计算

c# - 单独项目中 DAL 的连接字符串问题

c# - 将 Json 文档反序列化为 C# 对象

c# - 如何在 C# 中提取 xml 元素的路径?

java - Apache POI 设置日期格式并不总是在 Excel 中正确格式化

excel - 这不是我的问题的描述,但是Stackoverflow不允许我提交我的描述性标题

vba - Excel VBA基于单元格值的switch语句

如果单元格包含文本片段,Excel 2010 VBA 行宏条件格式

c# - NHibernate 动态创建/更改/删除表