应用程序脚本查找和替换,特定范围内的单元格内多次出现

问题描述 投票:0回答:1

我正在尝试搜索特定范围内的字符(“,”),并用新字符(“|”)替换所有出现的该字符。例如,当前的单元格可能有“苹果、香蕉、橙子、坚果”,我希望运行脚本后单元格有“苹果|香蕉|橙子|坚果”。我需要脚本仅在指定的列中运行。

我对脚本很陌生,并且将来自不同线程的一些代码拼凑在一起(部分)。问题是代码(如下所示)仅替换单元格中字符的第一个实例。在我的示例中,产品不是所需的“苹果|香蕉|橙子|坚果”,而是“苹果|香蕉、橙子、坚果”

我不知道如何使代码循环返回,直到指定范围内的单元格中的所有“,”都被替换。我正在使用的代码如下:

function onOpen() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange("g2:h998");
  var to_replace = ", ";
  var replace_with = "|";
  replaceInSheet(sheet, range, to_replace, replace_with);
}

function replaceInSheet(sheet, range, to_replace, replace_with) {
  //Confirm
  var ui = SpreadsheetApp.getUi();
  var spread = SpreadsheetApp.getActiveSpreadsheet();

  var result = ui.alert(
    "Will update to add " + replace_with + ".",
    'Are you sure you want to continue?',
    ui.ButtonSet.YES_NO);

  // Process the user's response.
  if (result == ui.Button.YES) {

    // User clicked "Yes".
    spread.toast("Will update", "ALERT");

    var data = range.getValues();

    var oldValue = "";
    var newValue = "";
    var cellsChanged = 0;


    for (var row = 0; row < data.length; row++) {
      for (var item = 0; item < data[row].length; item++) {
        oldValue = data[row][item];
        newValue = data[row][item].replace(to_replace, replace_with);
        if (oldValue != newValue) {
          cellsChanged++;
          data[row][item] = newValue;
        }
      }
    }

      range.setValues(data);
      spread.toast(cellsChanged + " cells changed", "STATUS");
  }

  else {
    // User clicked "No" or X in the title bar.
    spread.toast("No action taken", "ABANDONED");
  }
}
google-sheets google-apps-script replace
1个回答
0
投票

全部替换为文本查找器

function myfunk() {
  const to_replace = ", ";
  const replace_with = "|";
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const rg = sh.getActiveRange();
  rg.createTextFinder(to_replace).replaceAllWith(replace_with);
}
© www.soinside.com 2019 - 2024. All rights reserved.