0

我有 2 个变量需要在电子表格的数百页上更新。但我只需要在每个页面的单元格 B1 中更改它,而不需要任何其他单元格。如果 B1 是 Apple,我需要它说 Red Apple,如果 B1 是 Banana,我需要它说 Yellow Banana。

function run() {
runReplaceInSheet();
replaceInSheet();
}

function runReplaceInSheet() {

var spreadsheet = SpreadsheetApp.openById("ID"); 
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for ( var i = 0 ; i<sheets.length ; i++) {
var sheet = sheets[i];
// Fetch the range of cells 
var dataRange = sheet.getRange(startRow, 1, 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 values = sheet.getDataRange().getValues();  

// Replace Names

replaceInSheet(values, 'Apple', 'Red Apple');

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


}
}

这是我尝试使用的更新代码,它不断超时。

function run() {
runReplaceInSheet();
replaceInSheet();
}

function runReplaceInSheet() {

var spreadsheet = SpreadsheetApp.openById("ID"); 
var sheet = SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]); 
var startRow = 1; // First row of data to process
var numRows = 1; //  number of rows to process
// Fetch the range of cells 
var dataRange = sheet.getRange(startRow, 1, 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 value = sheet.getRange('B1').getValue();  

// Replace Names

replaceInSheet(values, 'Apple', 'Red Apple');

//write the updated values to the sheet, again less call;less overhead
sheet.getRange('B1').setValue(value);         

}
}

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;


}
}
4

1 回答 1

1

对于电子表格中的每个工作表,问题中的代码都会获取所有值,但您只需要替换单个单元格的值。

此外,替换功能在所有单元格中进行替换。

获取 B1 的值而不是

var values = sheet.getDataRange().getValues();  

利用

var value = sheet.getRange('B1').getValue();  

那么您可以使用比较值来查看是否需要替换,如果需要,而不是

sheet.getDataRange().setValues(values); 

你可能会使用

sheet.getRange('B1').setValue(value); 
于 2021-03-15T23:36:20.750 回答