谷歌表脚本 - 选择多个a1表示法范围

时间:2016-01-07 15:36:10

标签: google-apps-script google-sheets

我选择使用谷歌应用脚​​本批量更新行颜色。但是我无法使用通常的范围功能,因为要着色的行不是连续的。所以我认为,a1表示法会有所帮助但不幸的是,我看起来只能通过一个a1表示法而不是多个表达式:

var a1Notations="A1:C1,A3:C3,A10,C10";
sheet.getRange(a1Notations).setBackground("red");

但是我得到了#34;未找到范围"错误。

任何想法我如何才能使这项工作?

谢谢!

4 个答案:

答案 0 :(得分:1)

将范围符号放入数组中,然后遍历数组:

function setMultiRanges() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getActiveSheet();

  var a1Notations=["A1:C1","A3:C3","A10","C10"];

  var i=0,
      arryLngth = a1Notations.length;

  for (i=0;i<arryLngth;i+=1) {
    //Logger.log(a1Notations[i]);
    //Logger.log(typeof a1Notations[i]);

    sh.getRange(a1Notations[i]).setBackground("red");
  };
};

答案 1 :(得分:1)

要多选多个范围并更改颜色:

var sheet = SpreadsheetApp.getActiveSheet();
var rangeList = sheet.getRangeList(['A1:C1','A3:C3','A10','C10']);
sheet.setActiveRangeList(rangeList).setBackground("red");

如果要在对话框中键入列表:

function promptRangesList() {
  var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Comma-separated ranges list', 'E.g.: A1:C1,A3:C3,A10,C10 or C3,C7,C17,C56', ui.ButtonSet.OK_CANCEL);
  Logger.log(response.getSelectedButton());
  // Process the user's response.
  if (response.getSelectedButton() == ui.Button.OK) {
    if (response.getResponseText()!=='') {
      var list = response.getResponseText().split(',');
      Logger.log(list);
      var rangeslist = SpreadsheetApp.getActiveSheet().getRangeList(list).setBackground("red");
      Logger.log(rangeslist);
      rangeslist.activate(); 
    } else {
      Logger.log('getResponseText empty');
    }    
  } else if (response.getSelectedButton() == ui.Button.CANCEL) {
    Logger.log('CANCELED');
  } else {
    Logger.log('The user clicked the close button in the dialog\'s title bar.');
  }  
}

参考:

Class RangeList - Selects the list of Range instances

Class Sheet - Sets the specified list of ranges as the active ranges in the active sheet.

Prompt dialogs - A prompt is a pre-built dialog box that opens inside a Google Docs, Sheets, or Forms editor.

答案 2 :(得分:0)

独立设定每个范围

 sheet.getRange("A1:C1").setBackground("red");
 sheet.getRange("A3:C3").setBackground("red");
 sheet.getRange("A10:C10").setBackground("red");

答案 3 :(得分:0)

根据the doc of Google Sheets' API V4,选择多个范围的方法是传递一系列范围。

var ranges = ["'EVERYTHING'!A:A", "'EVERYTHING'!Z:Z"];

// I use Node.js, so my call to the API looks like this:
service.spreadsheets.values.batchGet({
    spreadsheetId: spreadsheetId,
    ranges: ranges
}, function(err, result) { ...

然后你得到的是一系列数据,[{first range},{second range},{etc ...}]