查找并替换单元格中文本的代码-Google表格

时间:2019-12-05 13:19:22

标签: javascript google-sheets

从此站点借用了此代码-谢谢。完美运行。

要替换的文本各不相同,而不是每次都设置名称(如下),我可以引用两个需要替换的单元格吗? -它们在同一工作簿的另一个电子表格中  replaceInSheet(values,'Abbotsfords','Abbotsford');

预先感谢

function runReplaceInSheet() {

    var spreadsheet = SpreadsheetApp.openById("id entered"); // UPDATE ID
    var sheet = SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]); // UPDATE number in square 
    brackets
    var range = sheet.getRange("Q3:Q");
    //  get the current data range values as an array
    //  Lesser calls to access the sheet, lower overhead 
    var startRow = 3; // First row of data to process. start at Row 3
    var numRows = 17; // Specify what column to look at. This is looking at Column Q
    // Fetch the range of cells 
    var dataRange = sheet.getRange(startRow, 4, numRows, 1) // Numbers of rows to process
    // Fetch values for each row in the Range
    var data = dataRange.getValues();
    for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var v = row[3]; // edit: don't need this
    var values = range.getValues();  

    // Replace Names

    replaceInSheet(values, 'Abbotsfords', 'Abbotsford');

    //write the updated values to the sheet, again less call;less overhead
    range.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;


}
}

0 个答案:

没有答案