2

免责声明:我是Newb。我对脚本有点了解,但编写它对我来说很痛苦,主要是循环和数组,因此如下。

我正在尝试从特定列(在本例中为 H [8])中提取所有数据,检查该列中每个单元格的值,如果是,将其更改为是;如果是n,则改为No;如果它是空的,请不要理会它并移动到下一个单元格。

这是我到目前为止所拥有的。像往常一样,我相信我已经很接近了,但是我无法设置活动单元格的值,也看不出我在哪里搞砸了。在某一时刻,我实际上在列中将 ever 值更改为 Yes(非常感谢在这些情况下撤消)。

工作表示例

..... COL-H  
r1... [service] <-- header  
r2... y  
r3... y  
r4... n  
r5... _  <-- empty  
r6... y  

意图:将所有 y 更改为 Yes,将所有 n 更改为 No(跳过空白单元格)。

到目前为止我已经尝试过

功能尝试1

function Thing1() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet");
  var lrow = ss.getLastRow();
  var rng = ss.getRange(2, 8, lrow - 1, 1);
  var data = rng.getValues();

  for (var i=0; i < data.length; i++) {
    if (data[i][0] == "y") {
      data[i][0] == "Yes";
    }
  }
}

功能尝试2

function Thing2() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet");
  var lrow = ss.getLastRow();
  var rng = ss.getRange(2, 8, lrow - 1, 1);
  var data = rng.getValues();

  for (var i=0; i < data.length; i++) {
    if (data[i][0] == "n") {
      data.setValue("No");
    } else if (data[i][0] == "y") {
      data.setValue("Yes");
    }
  }
}

用法

一旦我在这里完成,我想修改函数,以便我可以定位任何列并将一个值更改为另一个(我已经有一个方法,但我需要能够设置值)。就像这样:=replace(sheet, col, orig_value, new_value)。我也会在下面发布。

在此先感谢您的帮助。


用于在列中搜索和替换的完整代码

function replace(sheet, col, origV1, newV1, origV2, newV2) {
  // What is the name of the sheet and numeric value of the column you want to search?
  var sheet = Browser.inputBox('Enter the target sheet name:');
  var col = Browser.inputBox('Enter the numeric value of the column you\'re searching thru');

  // Add old and new targets to change (Instance 1):
  var origV1 = Browser.inputBox('[Instance 1:] What old value do you want to replace?');
  var newV1 = Browser.inputBox('[Instance 1:] What new value is replacing the old?');

  // Optional - Add old and new targets to change (Instance 2):
  var origV2 = Browser.inputBox('[Instance 2:] What old value do you want to replace?');
  var newV2 = Browser.inputBox('[Instance 2:] What new value is replacing the old?');

  // Code to search and replace data within the column
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
  var lrow = ss.getLastRow();
  var rng = ss.getRange(2, col, lrow - 1, 1);
  var data = rng.getValues();

  for (var i=0; i < data.length; i++) {
    if (data[i][0] == origV1) {
      data[i][0] = newV1;
    } else if (data[i][0] == origV2) {
      data[i][0] = newV2;
    }
  }
  rng.setValues(data);
}

希望这可以帮助那里的人。再次感谢@ScampMichael!

4

1 回答 1

5

名为 data 的数组是根据范围中的值创建的,并且在创建后独立于电子表格,因此更改数组中的元素不会影响电子表格。您必须修改数组,然后将整个数组放回原来的位置。

  for (var i=0; i < data.length; i++) {
    if (data[i][0] == "n") {
      data[i][0] = "No";
    } else if (data[i][0] == "y") {
      data[i][0] = "Yes";
    }
  }
rng.setValues(data); // replace old data with new
}
于 2013-04-12T22:07:32.467 回答