AppScript For Google Form

47 Views Asked by At

I want to make my code read a sheet containing IDs, and when someone enters the wrong ID, the code removes the unmatched response from the Google response sheet. The code needs to read the ID numbers in the first column.

When someone fills out the Google form, the first question is ID Number. When they fill out the form and click submit, if the ID number they entered does not match an ID number in the Google sheet, then the code needs to remove the form responses of the Google form. The code should only keep submitted forms if the ID number is present in the Google sheet. It currently does not do that.

This is my code:

function removeUnmatchedResponses() {
  try {
    // Replace 'SPREADSHEET_ID' with the ID of your Google Sheets document
    var spreadsheet = SpreadsheetApp.openById('1sh5dcQJPRJtbFpe7qVjpo7yIUwi5_mCGKrAnhWm-Hng');
    
    // Get the "IDs" sheet by index (assuming it's the first sheet)
    var idsSheet = spreadsheet.getSheets()[0]; // Change the index if the "IDs" sheet is not the first one

    // Check if "IDs" sheet exists
    if (!idsSheet) {
      throw new Error("IDs sheet not found.");
    }

    // Get the Form Responses sheet
    var formResponsesSheet = spreadsheet.getSheetByName("Form Responses");
    
    // Check if Form Responses sheet exists
    if (!formResponsesSheet) {
      throw new Error("Form Responses sheet not found.");
    }

    // Get all the IDs from the "IDs" sheet
    var idsRange = idsSheet.getRange("A:A");
    var idsValues = idsRange.getValues().flat().filter(Boolean); // Assuming IDs are in column A

    // Get the data range from the Form Responses sheet
    var formResponsesRange = formResponsesSheet.getDataRange();
    var formResponsesValues = formResponsesRange.getValues();

    // Separate matched and unmatched responses
    var matchedResponses = [];
    var unmatchedResponses = [];

    for (var i = 0; i < formResponsesValues.length; i++) {
      var responseId = formResponsesValues[i][0]; // Assuming the ID is in the first column of the Form Responses sheet
      if (idsValues.includes(responseId)) {
        matchedResponses.push(formResponsesValues[i]);
      } else {
        unmatchedResponses.push(formResponsesValues[i]);
      }
    }

    // Clear existing data in the Form Responses sheet
    formResponsesRange.clear();

    // Write back the matched responses
    if (matchedResponses.length > 0) {
      formResponsesSheet.getRange(1, 1, matchedResponses.length, matchedResponses[0].length).setValues(matchedResponses);
    }

    // Append the unmatched responses
    if (unmatchedResponses.length > 0) {
      formResponsesSheet.getRange(formResponsesSheet.getLastRow() + 1, 1, unmatchedResponses.length, unmatchedResponses[0].length).setValues(unmatchedResponses);
    }

    Logger.log("Unmatched responses removed successfully.");
  } catch (error) {
    Logger.log("Error: " + error.message);
  }
}
0

There are 0 best solutions below