I'm creating a stat sheet for my D&D campaign and would like to keep track of how much damage each character deals. I was hoping to create a macro that's attached to a button that adds the value of one cell to the current value of another cell.
Example: The current value of cell B4 is 12. I input 23 into cell H4 and press the button. Cell B4 is now 35 and the value of cell H4 is reset to 0.
Thank you in advance :)
CodePudding user response:
Welcome blooturtleduck. This script would do exactly what you've asked for:
function myFunction() {
currentValue = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(4,2).getValue(); //get value from B4 (B = column 2)
newValue = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(4,8).getValue(); //get value from H4 (H = column 8)
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(4,2).setValue(currentValue newValue); //set B4 to the sum of those two values
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(4,8).clear(); //Clear H4
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('myFunction', 'myFunction')
.addToUi();
}
The first function changes the cell values. The second function adds a custom menu so you can call the function from the Google Sheets menu.
If you'd prefer to click a button image in the spreadsheet, check out instructions here: https://developers.google.com/apps-script/guides/menus
I recommend having a read of best practices for Google Apps Script: https://developers.google.com/apps-script/guides/support/best-practices
For example, rather than calling individual getValue operations for each cell, it is usually much faster to call one getValues for a whole sheet, do all of the processing you want, and then one setValues at the end (because each call from AppsScript to Sheets takes time).