gScript:setvalue到多个工作表

时间:2017-03-08 14:35:33

标签: google-sheets

尝试使用该用户提示的响应并使用该提示响应设置一系列单元格的值。我使用下面的代码在sheet [0]上工作。

function CopyToColumnE() {
  //Get current spreadsheet and sheet0
  var source = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = source.getSheets()[0];


  //Prompt for the data to fill into the range
  var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Enter the value to copy to all Column E cells');
  var value = response.getResponseText();

  //Set the range of cells
  var range37 = sheet.getRange("E3:E7");
  var range1115 = sheet.getRange("E11:E15");
  var range1923 = sheet.getRange("E19:E23");

  // Call the setValue method on range and pass in our promoted response
  range37.setValue(value);
  range1115.setValue(value);
  range1923.setValue(value);
}

现在......如何在所有工作表中设置相同的范围?不只是sheet [0],所有表格。使用此脚本的用户可以随心所欲地添加/删除工作表。

因此,提示用户注意价值'并设置sheet0.ranges,sheet1.ranges,sheet2.ranges ... etc

修改 在Karl_S的有用提示后,我最终得到了这段代码,它确实有效!

function CopyToColumnE() {
  //Get current spreadsheet and sheet
  var source = SpreadsheetApp.getActiveSpreadsheet();
  //Prompt for the data to fill into the range
  var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Enter the value to copy to all Column E cells');
  var value = response.getResponseText();
  //Loop through ALL sheets in spreadsheet/workbook
  var allsheets = source.getSheets();
    for (var s in allsheets){
    var sheet=allsheets[s]



  //Set the range of cells
  var range37 = sheet.getRange("E3:E7");
  var range1115 = sheet.getRange("E11:E15");
  var range1923 = sheet.getRange("E19:E23");

  // Call the setValue method on range and pass in our promoted response
  range37.setValue(value);
  range1115.setValue(value);
  range1923.setValue(value);
}
}

1 个答案:

答案 0 :(得分:0)

.getSheets()将获取所有工作表,因此请尝试全部读取并循环遍历每个工作表

var allSheets = source.getSheets();

for (i in allSheets) {
  sheet = allSheets[i];
  // As a sample, this will give you the sheet name for the current sheet:
  var mayName = allSheets[i].getName();

  //  Add your code to add the data to sheet inside the loop
}