首页 > 解决方案 > 查找和替换单元格范围 [示例脚本]

问题描述

我有一个示例脚本,它使用脚本运行查找和替换值。

我想知道我将如何调整这个现有的脚本来找到一系列单元格来替换文本 [不指定脚本中的文本,而是运行一列值来查找,第二列表示要做什么替换为]。

https://docs.google.com/spreadsheets/d/1zmY48XQT_esYji58pMbk7oJy6Vncr0Oh5urJiK3ka4U/edit#gid=0

这是最接近我的查询的,但无法复制 [循环不是我的强项]

谷歌脚本“替换”功能与范围

 function runReplaceInSheet(){
      var sheet = 
      SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
      //  get the current data range values as an array
      //  Fewer calls to access the sheet -> lower overhead 
      var values = sheet.getDataRange().getValues();  

      // Replace Staff Names
      replaceInSheet(values, 'This is a sentence.', 'This is a word');
      replaceInSheet(values, 'Hello my name is', 'Your name is');
      replaceInSheet(values, '.', '-');
      replaceInSheet(values, '!', '.');
      replaceInSheet(values, 'Bob', 'Sagget');

      // Write all updated values to the sheet, at once
      sheet.getDataRange().setValues(values);
    }

    function replaceInSheet(values, to_replace, replace_with) {
      //loop over the rows in the array
      for(var row in values){
      //use Array.map to execute a replace call on each of the cells in the 
      row.
      var replaced_values = values[row].map(function(original_value) {
      return original_value.toString().replace(to_replace,replace_with);
    });

    //replace the original row values with the replaced values
      values[row] = replaced_values;
      }
    }

我希望脚本在整个工作表中找到单元格 D21:D23 中的内容,并用 E21:E23 替换任何实例

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


尝试这个:

function findAndReplaceOnAllSheets() {
  var ss=SpreadsheetApp.getActive();
  var shts=ss.getSheets();
  for(var i=0;i<shts.length;i++) {
    shts[i].getRange('D21:D23').setValues(shts[i].getRange('E21:E23').getValues());
  }
}

我想我不明白你的问题。

这是什么意思呢?

在此处输入图像描述

如果您想给我们一个示例,请向我们展示更改前和更改后的文本,并清楚哪个是哪个。


推荐阅读