Advertisement
RemcoE33

Prudent_Evening1929

Apr 6th, 2023
359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const startrow = 3
  2.  
  3. function start() {
  4.   const ss = SpreadsheetApp.getActiveSpreadsheet();
  5.   const sheets = ss.getSheets()
  6.  
  7.   sheets.forEach(sheet => {
  8.     lock(sheet)
  9.   })
  10. }
  11.  
  12. function lock(sheet) {
  13.   const values = sheet.getRange(startrow, 1, sheet.getLastRow() - 2, 2).getValues();
  14.   const now = new Date().getTime()
  15.   let currentDate
  16.   let endrow
  17.  
  18.   for (let i = 0; i < values.length; i++) {
  19.     let [time, date] = values[i]
  20.     if (time == "") {
  21.       currentDate = date
  22.       continue
  23.     }
  24.  
  25.     //Pase the time
  26.     time = new Date(time)
  27.     time = Utilities.formatDate(time, Session.getScriptTimeZone(), "hh:mm:ss")
  28.     time = time.split(" ")[0]
  29.  
  30.     //Combine date and time
  31.     const dateTime = new Date(`${currentDate.toISOString().split("T")[0]} ${time}`)
  32.  
  33.     //Keep track of endrow
  34.     if (dateTime.getTime() <= now) {
  35.       endrow = startrow + i
  36.     }
  37.  
  38.     //Check if we have met a datetime that is great then now. Then set the lock to the previous recorded endrow.
  39.     if (dateTime.getTime() >= now && time != "" && endrow) {
  40.       //Remove lock
  41.       sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE).forEach(p => {
  42.         if (p.getDescription() == "AUTOLOCK") {
  43.           p.remove()
  44.         }
  45.       })
  46.  
  47.       //Set new lock
  48.       sheet.getRange(startrow, 1, endrow, sheet.getLastColumn()).protect()
  49.         .setDescription("AUTOLOCK")
  50.       break;
  51.     }
  52.   }
  53. }
  54.  
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement