Google App Script to Append Value from one Cell to

2019-08-31 05:27发布

问题:

I’ve been trying to figure out how to write a script which will take the value from one cell and append it to the end of a string of numbers in another cell of that same row. The newly appended number needs to be separated by a comma from the previously appended value, and the whole string needs to be wrapped between brackets. EX. [2,3,3,4.5,2.5,2.1,1.3,0.4]. The script will need to loop through all of the rows containing data on a named sheet beginning with the third row.

The above image is obviously just an example containing only two rows of data. The actual spreadsheet will contain well over a thousand rows, so the operation must be done programmatically and will run weekly using a timed trigger.

To be as specific as I can, what I need help with is to first know if something like the appending is even possible in Google App Scripts. I've spent hours searching and I can't seem to find a way to append a new value (ex. cell A3) to the current string (ex. cell B3) without overwriting it completely. In full disclosure; I'm a middle school teacher trying to put something together for my school.

回答1:

To be as specific as I can, what I need help with is to first know if something like the appending is even possible in Google App Scripts.

Seeing the expected result, it's inserting rather than appending, as the string should be added before the last character (]). Anyway, yes, this is possible by using JavaScript string handling methods.

  • Use getValue() to the get the cell values, both the Current GPA and the GPA History.
  • One way is to use replace

Example using pure JavaScript:

var currentGPA = 3.5
var gpaHistory = '[2,3.1,2.4]';
gpaHistory = gpaHistory.replace(']',','+currentGPA+']');
console.info(gpaHistory)

Once you get the modified gpaHistory, use setValue(gpaHistory) to add this value to the spreadsheet.