I spent the morning digging around for something similar.
Unfortunately the function call to UpdateFilter()
posted by wriddle2 didn't work. The function isn't defined in Apps Script for a Google Sheets project when I tried it today, April 15 2021. It was pretty close to what I ended up using, though.
In my case, I'm pulling information in from another spreadsheet and merging it with information in the one where the script runs (Google, can we PLEASE have JOIN capability in the QUERY function?).
I'm sure that the original poster has long ago moved on with their life, but I'll frame my answer here in that context anyway. This can be called from any function in an Apps Script project, it doesn't have to be in onFormSubmit()
.
function onFormSubmit(e) {
SpreadsheetApp.flush();
}
In my case, I can't know if the user will have a filter enabled in the first place, so I have a bit of extra code to save it, then remove and clear the sheet before inserting today's data, and re-add the filter if one existed beforehand. It looks something like this:
function myFunc() {
var spreadSheet = SpreadsheetApp.getActive();
var reportSheet = spreadSheet.getSheetByName('Report Sheet');
var columnCount = reportSheet.getLastColumn();
reportSheet.clearContents(); // I do this because each day gets a fresh report
if(reportSheet.getFilter()) {
var hadFilter = true;
var sheetFilter = reportSheet.getFilter();
var filterSettings = new Array(columnCount);
// Array indexed at 0, columns indexed at 1. A recipe for disaster!
for(var i = 0; i < columnCount; i++) {
filterSettings[i] = sheetFilter.getColumnFilterCriteria(i + 1);
}
// If you attempt to append data over a set of rows that had a filter still applied,
// things get weird. Hence removing and re-creating the filter.
sheetFilter.remove();
}
// Not going to bore you with the details;
var arrayOfCells = myCustomFunctionThatReturnsData();
reportSheet.getRange(1,1,arrayOfCells.length,columnCount).setValues(arrayOfCells);
if(hadFilter) {
var sheetFilter = reportSheet.getDataRange().createFilter();
for(var i = 0; i < columnCount; i++) {
sheetFilter.setColumnFilterCriteria(i + 1, filterSettings[i])
}
// Here's the magic! Without this, you get a filter that looks
// like it should work but doesn't actually apply.
SpreadsheetApp.flush();
}
}