简体   繁体   中英

Google Sheets activate a cell within a loop

I have a loop that does what I want, but I would like to set an active cell in each sheet so I don't have to click it each time as I cycle through.

I've tried two ways that seem to make sense, but they both only work on the last sheet in the loop:-

function setDraft() {

//msg box to confirm relevant sheets are hidden, thus excluded from code
  var response = Browser.msgBox("SET AS DRAFT","Have you hidden sheets you don't want marked as draft?", Browser.Buttons.YES_NO);
  if(response=="no")
    return;
  else if(response=="cancel")
    return;
  else

//loop and code for Visible sheets  
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();

  for (var s in allsheets){
  var sheet=allsheets[s]
  var date = sheet.getRange('I1')

  if (sheet.isSheetHidden()!= true) {   
//sheet.setActiveRange(date);
  sheet.setActiveSelection(date);
  sheet.getRange('I5').setValue('DRAFT');
       }    
    }
}

Can anyone please let me know where I'm going wrong?

Thanks in advance!

Using for...in in JS can lead to problems (more on that in this post ). Second, try using the built in UI class through the SpreadsheetApp class rather than the Browser buttons.

function setDraft() {
  var ui = SpreadsheetApp.getUi();
  var allsheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  //msg box to confirm relevant sheets are hidden, thus excluded from code
  var response = ui.alert("SET AS DRAFT","Have you hidden sheets you don't want marked as draft?", ui.ButtonSet.YES_NO);
  if(response == ui.Button.NO) {
    return;
  } else {
    for (var s=0; s<allsheets.length; s++){
      var sheet=allsheets[s]
      var date = sheet.getRange('I1')

      if (sheet.isSheetHidden()!= true) {   
        sheet.setActiveSelection(date);
        sheet.getRange('I5').setValue('DRAFT');
      }    
    }
  }
}

Use the sheet.activate() or range.activate() methods. Use sheet method if you only care to go to a specific sheet, but if you want the select a specific cell then use it with range . I have not tested with range, however, I know that if you use sheet.activate() then you will be brought to that sheet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM