增量字符串值Google表格

时间:2018-05-07 16:54:48

标签: google-sheets-macros

使用以下代码我无法将Google表格中的值增加为1。

function incrementCellValuesByOne() {
  // Increments the values in all the cells in the active range (i.e., selected cells).
  // Numbers increase by one, text strings get a "1" appended.
  // Cells that contain a formula are ignored.

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeRange = ss.getActiveRange();
  var cell, cellValue, cellFormula;

  // iterate through all cells in the active range
  for (var cellRow = 1; cellRow <= activeRange.getHeight(); cellRow++) {
    for (var cellColumn = 1; cellColumn <= activeRange.getWidth(); cellColumn++) {
      cell = activeRange.getCell(cellRow, cellColumn);
      cellFormula = cell.getFormula();

      // if not a formula, increment numbers by one, or add "1" to text strings
      // if the leftmost character is "=", it contains a formula and is ignored
      // otherwise, the cell contains a constant and is safe to increment
      // does not work correctly with cells that start with '=
      if (cellFormula[0] != "=") {
        cellValue = cell.getValue();
        cellValue =+cellValue
        cell.setValue(cellValue + 1);
      }
    }
  }
}

例如&#34; personalDataDOB_3&#34;需要成为&#34; personalDaTaDOB_4&#34;我正在寻找一种快速的方法,因为我现在需要通过输入来替换值。

1 个答案:

答案 0 :(得分:0)

您想要修改&#34; personalDataDOB_3&#34;特定细胞的个体数据,以及#34; personalDaTaDOB_4&#34;。如果我的理解是正确的,那么这个修改怎么样?

修改要点:

  • 当检索到&#34; personalDataDOB_3&#34;使用cellValue =+cellValue转换为数字,返回NaN。因此,即使添加了1,结果也是NaN
  • 如果要修改的字符串格式始终为&#34; personalDataDOB _#&#34;,如何将字符串分隔为_

为了反映以上几点,请按照以下步骤修改您的脚本。

来自:

if (cellFormula[0] != "=") {
  cellValue = cell.getValue();
  cellValue =+cellValue
  cell.setValue(cellValue + 1);
}

致:

if (cellFormula[0] != "=") {
  cellValue = cell.getValue();
  var temp = cellValue.split("_"); // Added
  temp[1] = Number(temp[1]) + 1; // Added
  cell.setValue(temp.join("_")); // Modified
}

注意:

  • 如果您要修改的字符串格式始终更改,请告诉我。

如果我误解了你的问题,我很抱歉。