Function for finding multiple values from an array and replace data in a specific column based on the matching IDs?

59 views Asked by At

I have an Event Scheduler spreadsheet where I need to add or remove employee's from column A in the query table, for each row I have a dropdown list to select names.I use a script that can find only one name at a time on the database sheet and replace it after clicking a buttom. The search engine is based on IDs (column A). I need this function to be able to get multiple names and replace them all at once instead. Can anyone help me please? This is the code I have for only one value.

function saveRecord7() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const formWS = ss.getSheetByName('Dashboard')
  const dataWS = ss.getSheetByName('Static_VDatabase_UID')
  const idCell = formWS.getRange('G7')
  const fieldRange =["AB7"]
  const clearcell = formWS.getRange('AB7')

  const id = idCell.getValue()
  if(id== ''){

    //createNewRecord()
    return
  }
  
   const cellFound = dataWS.getRange("A:A")
                  .createTextFinder(id)
                  .matchCase(true)
                  .matchEntireCell(true)
                  .findNext()

    if(!cellFound) return  
    const row = cellFound.getRow()            
  
   const fieldValues = fieldRange.map(f => formWS.getRange(f).getValue())
   fieldValues.unshift()
   dataWS.getRange(row,20,1,fieldValues.length).setValues([fieldValues])  

 clearcell.clearContent();
}
1

There are 1 answers

1
Gleb Gorokhov On BEST ANSWER
function saveRecordsBatch() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const formWS = ss.getSheetByName('Dashboard');
  const dataWS = ss.getSheetByName('Static_VDatabase_UID');

  // Assuming IDs start from G1 and values from AB1
  const idsRange = formWS.getRange('G1:G'); // Adjust the range as needed
  const valuesRange = formWS.getRange('AB1:AB'); // Adjust the range as needed

  const ids = idsRange.getValues().filter(String); // Remove empty rows
  const values = valuesRange.getValues().filter(String); // Remove empty rows

  if (ids.length !== values.length) {
    // Make sure each ID has a corresponding value
    throw new Error('Mismatch between IDs and values length');
  }

  ids.forEach((idArray, index) => {
    const id = idArray[0];
    if (id === '') {
      return; // Skip empty IDs
    }

    const cellFound = dataWS.getRange("A:A")
      .createTextFinder(id)
      .matchCase(true)
      .matchEntireCell(true)
      .findNext();

    if (!cellFound) return;
    const row = cellFound.getRow();

    // Assuming you want to replace the value in column 20
    dataWS.getRange(row, 20).setValue(values[index][0]);
  });

  // Clear the input ranges after processing
  idsRange.clearContent();
  valuesRange.clearContent();
}