mercredi 30 juin 2021

How do I prevent negative values in my script?

Background Info

  • I have a maximum of 15 hours available for work Monday – Friday.

  • Each day, from Monday – Thursday, I will work a random amount of hours between 0 – 8.

  • I do not need to work at least 1 hour Monday – Thursday.

  • On Friday, I will work whatever hours are left from the maximum of 15 hours available.

  • I must work at least 1 hour on Friday.

Formulas Used

  • Monday: RANDBETWEEN(0-8)

  • Tuesday: RANDBETWEEN(0-8)

  • Wednesday: RANDBETWEEN(0-8)

  • Thursday: RANDBETWEEN(0-8)

  • Friday: 15 – SUM(Monday:Thursday) <- Will use A1 notation

  • Total Hours: SUM(Monday:Friday) <- Will use A1 notation

Issues

  • The Friday cell will occasionally receive a negative number of hours worked.

Example Output of Issue

Output

Current Workaround

  • Update the values generated by RANDBETWEEN by pressing ‘DEL’ on an empty cell. This forces all the values to change.

    Repeat until a positive value is received in the cell for Friday

Google Sheet Settings

Goal

Have the cells update themselves automatically IF a negative value is received in the cell for Friday

Possible Solution/Thoughts

Is there a way to force RANDBETWEEN numbers to update via a formula?

If yes, is there a way to setup a WHILE loop that will update the RANDBETWEEN values UNTIL the cell for Friday has a positive number?

Tried a script but wasn’t able to get the cells to update at all.

function randomTotal() 
{
  var Monday = SpreadsheetApp.getActiveSheet().getRange('C4');
  var Tuesday = SpreadsheetApp.getActiveSheet().getRange('D4');
  var Wednesday = SpreadsheetApp.getActiveSheet().getRange('E4');
  var Thursday = SpreadsheetApp.getActiveSheet().getRange('F4');
  var Friday = SpreadsheetApp.getActiveSheet().getRange('G4');
  
  while(Friday < 0)
  {
    newTotal(Monday,Tuesday,Wednesday,Thursday);
    Monday.getValue();
    Tuesday.getValue();
    Wednesday.getValue();
    Thursday.getValue();
    Friday.getValue();
  }
}
function newTotal( Monday,Tuesday,Wednesday,Thursday)
{
  Monday.setFormula('=RANDBETWEEN(0,8)');
  Tuesday.setFormula('=RANDBETWEEN(0,8)');
  Wednesday.setFormula('=RANDBETWEEN(0,8)');
  Thursday.setFormula('=RANDBETWEEN(0,8)');
  Friday.setFormula('15-SUM(C4:G4)');
}



Aucun commentaire:

Enregistrer un commentaire