Search code examples
google-apps-scriptgoogle-sheetsmouseevent

Increment cell value by constant number using mouse click on Google Sheets


I would like to use mouse clicks as a way of incrementing or substracting values from cells on Gsheets I came across the following piece of code for excel which works perfectly but I need the equivalent code for Google sheets if possible. Thank you for your help in advance!

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)


    If Target.Cells.Count > 1 Then Exit Sub
    
    If Not Intersect(Target, Range("A1:A100")) Is Nothing Then
        Cancel = True
        Target = Target - 0.05
    End If


End Sub


Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)


    If Target.Cells.Count > 1 Then Exit Sub
    
    If Not Intersect(Target, Range("A1:A100")) Is Nothing Then
        Cancel = True
        Target = Target + 0.05
    End If


End Sub ```

Solution

  • You could create a button with "Insert - Drawing", and apply this script:

    function increment() {
      var range = SpreadsheetApp.getActiveRange()
      var value = range.getValue()
      
      if(value == ""){value = 1}
      else if(typeof(value)!="number"){SpreadsheetApp.getActive().toast("It's not a number");}
      else(value++)
      range.setValue(value)
    }
    

    If the selected cell is empty, it will asign 1; if it is text, it will return a prompt; and if it's a number will add 1

    enter image description here