Search code examples
google-apps-scriptgoogle-sheetsrowcelledit

How to update an existing row (instead of create a new one updated)


I created a sheet with a code capable to send a desired row from a sheet named "ASSISTANT" to another sheet called "DATA" using a condition (when typing a number in a specific cell). The idea is to assign cars to users registering the "date in" value when assigned, and adding the "date out" value when received back.

The problem I want to solve is that, when I assign the car to a user, the row submitted contains "number, name, number, date in" values, and when we receive the car the script submits again the same row containing the same previous values and adding the "date out" value onto a new row in DATA sheet, so in the end, I have two rows: the first when assigned, and the second when received back.

I want my script to search for the fisrt submitted row in "DATA" sheet and overwrite it with the new row values, instead of create one new.

Here is the sheet containing the code with the problem:

https://docs.google.com/spreadsheets/d/1X27afOLzvljYjM8IgkoM3f0jtpQHXDmZRm75VmLvAwY/edit#gid=0

As a hint, in the following link:

How to add data to a specific row in Google Sheets using Google Script

…a user named "Sandy Good" answered on that post to other member with a code showing how to search a row and "update" it by overwriting it. The problem is that I don´t know how to implement that code onto the one I wroted. Maybe that post is the key… or maybe not, I´d just want to know how to solve it.

I´m starting with programming and I tried to finish this script by myself, researching and trying, but now I'm stuck.


Solution

  • Solved with a workaround. The script will add a row in the first position on a sheet containing a general list. I have created a sheet per car, now the script will add a row in the first position for each car list, so it´s easy to find the last "date in" row for a car, is always the first. When want to write adding the "date out" the script just needs to overwrite the first row of the desired car (the sheet name containing that car list matches the car number).

     targetSheet.insertRowAfter(1);   // Specify first row of destination sheet for receive content
     targetSheet.getRange("A2").setValue(cell1);   // Insert that content
    

    The difference is that when you assign a car there is a "targetSheet.insertRowAfter(1)", when you receive it there is not.

    Well, nobody here at this post helped me. Anyway, I learned a lot reading other questions… and from other users kindly answers, so thank you everybody!