简体   繁体   English

在公式中使用变量来引用 Office 脚本中的最后一行

[英]Using a variable in a formula to refer to the last row in Office Scripts

Using Office Scripts (in Excel), I'd like to apply a formula to a new column in which the formula contains the function for finding the maximum value of an adjacent column.使用 Office 脚本(在 Excel 中),我想将公式应用于新列,其中公式包含 function 以查找相邻列的最大值。 The number of data points collected varies from experiment to experiment, so I don't want to set finite bounds for finding the maximum of the adjacent column (ie MAX(G2:G10)).收集的数据点数量因实验而异,因此我不想设置有限界限来查找相邻列的最大值(即 MAX(G2:G10))。

I'd like to ideally create a variable for the number of rows so that I could then calculate the maximum of the column, despite the changing number of data points collected across experiments, such as MAX(G2:G(numrows)).我想理想地为行数创建一个变量,这样我就可以计算列的最大值,尽管跨实验收集的数据点数量不断变化,例如 MAX(G2:G(numrows))。

I've tried applying something along the lines of:我试过按照以下方式应用一些东西:

 let rowCount = range.getRowCount();
 const numrows = rowCount

 selectedSheet.getRange("H1:H2").setFormulasLocal([["Air Flow (%)"], ["=(G2/MAX($G$2:$G(numrows)))*100"]]);

I know that this syntax isn't correct, as it just results in an error (#NAME?), and was wondering if there were any suggestions on which variable types could make this work (or other approaches all together).我知道这种语法不正确,因为它只会导致错误(#NAME?),并且想知道是否有任何关于哪些变量类型可以使这项工作(或其他方法一起)的建议。

Thanks in advance!提前致谢!

You can try the code below:您可以尝试以下代码:

function main(workbook: ExcelScript.Workbook) {
  let selectedSheet = workbook.getActiveWorksheet();
  let lastRow = selectedSheet.getRange("G1048576").getRangeEdge(ExcelScript.KeyboardDirection.up).getRowIndex() + 1;
  selectedSheet.getRange("H1:H2").setFormulas([["Air Flow (%)"], [`=(G2/MAX($G$2:$G${lastRow}))*100`]]);
}

I determine the lastRow by going to the last cell in column G and then doing the programming equivalent of hitting the ctrl key and pressing the up arrow on my keyboard.我通过转到 G 列中的最后一个单元格然后执行相当于按下 ctrl 键并按下键盘上的向上箭头的编程来确定lastRow From here, I use getRowIndex() to get the row index and add one to it.从这里开始,我使用getRowIndex()获取行索引并将其加一。 I need to do that since row indexes start at zero instead of at one like row numbers.我需要这样做,因为行索引从零开始,而不是像行号那样从一开始。

Once I have the lastRow, I can update the string to use the lastRow variable.获得 lastRow 后,我可以更新字符串以使用 lastRow 变量。 From there, you can use setFormulas() to write the value / formula.从那里,您可以使用setFormulas()来编写值/公式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM