I've been searching for quite a while so hopefully no one else has asked this.
I have a Google Spreadsheet with two sheets, one a sort of database containing form submissions and the other a way for users to interact with submissions one at a time.
Basically I want users to be able to make changes to a submission and save them back to the same line that they came from in the original sheet.
I have the code to send the changes back but I can't figure out how to get the coordinates of the correct row:
function saveChanges() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getSheets()[0];
var destination = ss.getSheets()[1];
var range = source.getRange("A40:BL40");
// Find coordinates of the row where value of cell A40 matches a cell in A:A in second spreadsheet
// This copies the data in A40:BL40 in the source sheet to
// D4:F6 in the second sheet
range.copyValuesToRange(destination, 1, 64, 16, 16);
}
At the moment the data is just written to the coordinates "1, 64, 16, 16" which just points to a currently empty row - ideally I'd change that to a variable with the right coordinates.
The value of cell A40 is a unique ID and ideal for searching the second sheet but I can't figure out how.
I'm very new to Javascript so any help would be greatly appreciated.
To find your matching value in the form response sheet, you must loop through the range to find a match. There are a number of ways to do that, I'll show a couple.
Here's a version of your
saveChanges()
function that will get all the data from your destination sheet, look through it's column A for a match to the value inA40
, then update the data in that row.Here's another way to do it. This time, we don't read all the data in the destination sheet, only the info in column A. To be able to take advantage of array lookup methods, the two-dimensional array retrieved via
.getValues()
needs to be transposed first - so we use a helper function to do that. (I'm using thetranspose()
function from this answer.)The second approach has fewer lines of code, but should be a bit slower than the first one because of the
transpose()
function which touches every element in column A before performing a search with.indexOf()
. (The first approach searched in place, and exited once a match was found, so it actually does less work.)In both examples, I've tried to limit the calls to google's services as much as possible. Alternatively, you could read info from the spreadsheets inside the search loop, which would be much slower, but would avoid the
+1 / -1
mental gymnastics needed to keep 0-based arrays aligned with 1-based rows and columns.