简体   繁体   中英

Delete rows containing value from another sheet in Google Sheets using Apps Script

I have two spreadsheets named 'Database' and 'Form'.

I'd like to delete rows in 'Database' sheet if their 'Date' column contains matching value with cell 'C2' of 'Form' sheet using Apps Script. Here's what I have:

 function submitFormData() { const sheet = SpreadsheetApp.getActiveSpreadsheet(); const ui=SpreadsheetApp.getUi(); const form = sheet.getSheetByName("Form"); const database = sheet.getSheetByName("Database"); const date = form.getRange("C2").getValue(); // Get date value from cell "C2" of 'Form' sheet const databaseDates = database.getRange("A2:A").getValues(); // Get all values in 'Date' column of 'Database' sheet const blankRow = database.getLastRow()+1; const lastRow = database.getLastRow(); // Loop below checks for and deletes rows that meet the stated condition: for ( var i = 2; i <= lastRow; i++){ if(databaseDates[i] == date){ database.deleteRow[i]; } } // Regardless, paste newly submitted data onto blank rows: database.getRange(blankRow,1,3).setValue(form.getRange("C2").getValue()); database.getRange(blankRow,2,3).setValues(form.getRange("B4:B6").getValues()); database.getRange(blankRow,3,3).setValues(form.getRange("C4:C6").getValues()); ui.alert("New Data Saved"); }

For whatever reason, the 'for loop' fails to validate any condition so the script simply jumps to execute the setValue() operations below the loop. Here's an illustration of what I'm trying to achieve: desired sheet result

Being a complete newbie in scripting and actually to programming overall, I suspect it's a mistake in writing the Javascript arrays for the 'for loop' etc - but then things got even weirder after I literally copy-pasted this tutorial on a new sheet just to test if it's mainly my poor scripting ability or potentially a bug in the system: https://codewithcurt.com/how-to-clear-delete-insert-and-replace-row-using-google-apps-script/

..and you guessed right, I couldn't even make the deleteRow() function in this tutorial to work.

Other things to note:

  1. I've cleared browser cookies, refreshed my sheets, and both browser (Brave) and OS (MacOS) are up-to-date
  2. The data format in cell "C2" of 'Form' sheet and that in 'Date' column of 'Database' sheet is the same (Date format)

Lastly, link to a dummy sheet: https://docs.google.com/spreadsheets/d/1U4RaP7TG5_zfpROQ2ghAG3KKARKjK_YDc7KT02_0F_k/copy

Appreciate the help!

The short story is Google Apps Script will sometimes run spreadsheet calls out of order to optimize the work. You can prevent this using SpreadsheetApp.flush() . Try adding it right under your for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM