I'm still SUPER new to Google Sheets, I've mostly just programmed in VBA before this.
The project I'm working on is for a D&D type game, wherein the DM will use Sheet to record damage dealt to the monster. Basically the DM types the damage, clicks the calculate button, then the code sums up the current damage to baddie.
The code works perfectly. The problem I'm having is a human one. There is a tendency to click the "calculate" button before closing the cell.
For instance, the DM types 31 in the cell and immediately clicks "calculate" before hitting enter. This prevents the damage from being recorded properly and I can't figure out the code to make the cell close first.
Here is my current code:
function DamageRecordEnemy1Copy1() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A1').activate();
var DamageLocation = spreadsheet.getRange('Q4');
var DamageLogLocation = spreadsheet.getRange('Q5');
var DamageLocationValue = DamageLocation.getValue();
var DamageLogLocationValue = DamageLogLocation.getValue();
var NewDamage = DamageLocationValue + DamageLogLocationValue;
DamageLocation.activate();
spreadsheet.getCurrentCell().setValue(NewDamage);
DamageLogLocation.activate();
spreadsheet.getCurrentCell().setValue("");
spreadsheet.getRange('A1').activate();
}
Any idea how to solve the issue? Much appreciated!
Thanks for the help everyone, here is what I ended up doing:
function onEdit(e){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = e.range;
var DamageLocation = spreadsheet.getRange('Q4');
var DamageLogLocation = spreadsheet.getRange('Q5');
var DamageLocationValue = DamageLocation.getValue()
var DamageLogLocationValue = DamageLogLocation.getValue()
var allRows = [5];
var allColumns = [17, 20, 23, 26, 29, 32];
var EditRow = range.getRow()
var EditColumn = range.getColumn()
if (allColumns.indexOf(EditColumn) > -1)
{
if (allRows.indexOf(EditRow) > -1)
{
var BadDamage = spreadsheet.getRange(EditRow-1,EditColumn)
var BadDamageLog = spreadsheet.getRange(EditRow,EditColumn)
var DamageCalc = BadDamage.getValue() + BadDamageLog.getValue()
BadDamage.setValue(DamageCalc);
BadDamageLog.setValue("");
}
}
};
Replace the "button" with insert->checkbox then use the OnEdit function to check if that cell was set to true, execute your button code and set it back to false. The reason this will work is because Drawings are on it's own layer but the checkbox will force them to have the "hit enter" behavior.