Search code examples
javascriptgoogle-sheetstriggers

How to set a Google Sheets' Cell Note based off a Cell Value that begins with a Plus Sign


In a Google Apps script for the Google Sheet, I have this code with an OnEdit Trigger. It updates a cell's Note based off the value I pick from a drop down list, which was created for the cell using a "Data Validation" (Dropdown from Range).

The values from a separate that the dropdown contain, some have a + in front of them eg. +1 to modifier

I have tried formatting the values for the dropdown range eg. ="+1 to modifier

Theerafter the dropdown chosen value itself does not cause an error when modified as above.

But then the following Apps Script, used to set the chosen dropdown value as a note, breaks and the note is not added, shows error:

function addNotescToRange() {
// Get the "GraveLayout" sheet
const sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GraveLayout");

// Define the range (A1:B2) (to set Notes for each cell based off its value)
const range1 = sheet1.getRange("A1:B2");

// Get the values in the range as a two-dimensional array
const values = range1.getValues();

// Loop through each cell in the range
  for (let i = 0; i < values.length; i++) {
    for (let j = 0; j < values[i].length; j++) {
      const cell = range1.getCell(i + 1, j + 1); // +1 for zero-based indexing
      const value = values[i][j];

      // Set the note for the cell using its value
      cell.setNote(value);
    }

}
}

I added the apostrophe manually to append it to the value in this final part of the code but the note still errors:

// Set the note for the cell using its value 
cell.setNote('"' & value);

Solution

  • In GAS, concatenation uses not &, but +. That is, if you want to add an apostrophe before the value, then the code should not be cell.setNote(' " ' & value), but cell.setNote(" ' " + value). But this will not help you, since the problem arises because you use ="+1 to modifier" in the value range for the dropdown menu. If this particular spelling (as a formula) is not important to you, then use the spelling '+1 to modifier (as text). In this case, the value is understood correctly, no error occurs, and the note is set correctly. I corrected the values in the range E4:E5 in your spreadsheet and now everything works fine.