简体   繁体   English

Google电子表格脚本-迭代活动选择的行,但所有列

[英]Google spreadsheet Script - iterate on rows of active selection, but all columns

I have read many similar questions but I still can't get my code to work and I believe this is because of a slight difference in what I want to achieve : 我已经阅读了许多类似的问题,但是我仍然无法使我的代码正常工作,我相信这是因为我要实现的目标略有不同:

I want to perform iterations on the rows that correspond to the currently selected cells (I don't care about the cells themselves, just about their row). 我想在与当前所选单元格相对应的行上执行迭代(我不在乎单元格本身,仅在乎它们的行)。 I also need to reach cells that are outside the current selection, but in the same row. 我还需要访问当前选择之外但在同一行中的单元格。

Eg suppose I select A2:A3 in my spreadsheet, then I want to "recognize" I'm on rows 2 and 3, and perform operations like 例如,假设我在电子表格中选择了A2:A3,然后我想“识别”我在第2行和第3行,并执行类似

E2 = A2 + B2 + C2 * D2
E3 = A3 + B3 + C3 * D3

So far I was trying something like this but it doesn't seem to work 到目前为止,我正在尝试类似的方法,但是它似乎没有用

function myfunction(){
  var range = sheet.getActiveRange()
  var firstRow = range.getRow()
  var numRows = range.getNumRows();

  for (var i = 0; i < numRows; i++) {
    var absoluteRow = firstRow + i

NOTE : actually I believe the script itself is good, but the way I activate it is maybe the problem : 注意:实际上,我相信脚本本身是好的,但是激活它的方式可能是问题所在:

I generate a new menu item "MyFunction" in the top toolbar, and I attached my function to this menu item, but is it passing the activeRange correctly ? 我在顶部工具栏中生成了一个新的菜单项“ MyFunction”,并将函数附加到了此菜单项,但是它正确传递了activeRange吗?

SpreadsheetApp.getUi()
  .createMenu("MyMenu")
  .addItem("MyFunction","myFunction")
  .addToUi()

This code works properly for me 该代码对我来说正常工作

  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getActiveRange()
  var firstRow = range.getRow()
  var numRows = range.getNumRows();
  Logger.log("firstRow "+firstRow);
  Logger.log("numRows "+numRows);

  for (var i = 0; i < numRows; i++) {
    var absoluteRow = firstRow + i;
    Logger.log("absoluteRow "+absoluteRow); 
  }  

The results: 结果:

[16-09-01 13:44:44:762 EEST] firstRow 2
[16-09-01 13:44:44:763 EEST] numRows 5
[16-09-01 13:44:44:764 EEST] absoluteRow 2
[16-09-01 13:44:44:764 EEST] absoluteRow 3
[16-09-01 13:44:44:765 EEST] absoluteRow 4
[16-09-01 13:44:44:765 EEST] absoluteRow 5
[16-09-01 13:44:44:766 EEST] absoluteRow 6

Please see if you receive the proper results when you launch it from the script editor. 从脚本编辑器启动它时,请查看是否收到正确的结果。

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

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