Validate and Clean Data in Google Sheets with Apps Script
Dirty data causes bad decisions. Apps Script can automate the tedious work of validating, cleaning, and standardising data in your spreadsheets — far more powerfully than built-in data validation alone.
Trim whitespace from all cells
functiontrimAllCells(){const sheet =SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();const range = sheet.getDataRange();const values = range.getValues();const cleaned = values.map(row=> row.map(cell=>typeof cell ==='string'? cell.trim(): cell)); range.setValues(cleaned);Logger.log('Trimmed whitespace from all cells.');}
functionremoveBlankRows(){const sheet =SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();const data = sheet.getDataRange().getValues();let removed =0;// Iterate from bottom to top to avoid index shiftingfor(let i = data.length-1; i >=1; i--){const isEmpty = data[i].every(cell=> cell ===''|| cell ===null);if(isEmpty){ sheet.deleteRow(i +1); removed++;}}Logger.log(`Removed ${removed} blank row(s).`);}
Run all cleaning functions in sequence
functioncleanAllData(){trimAllCells();standardiseEmails();flagInvalidEmails();highlightDuplicates();removeBlankRows();Logger.log('Full data clean complete.');}
Tips
Always work on a copy of your data the first time you run a cleaning script.
Reading and writing the entire range at once (with getValues() / setValues()) is much faster than cell-by-cell operations.
Use setBackground(null) to clear highlights rather than setBackground('#ffffff') — it respects the sheet's default theme.
Combine with an onEdit trigger for real-time validation as data is entered.