Home > Mobile >  How to loop through cells in Google Sheets and log information if specific variables exist
How to loop through cells in Google Sheets and log information if specific variables exist

Time:03-11

You will need this link to solve this: - https://docs.google.com/spreadsheets/d/11PjVSWPfqOBPSej3AlQ-_T8Bws66kevR08Q2NRTmVcE/edit?usp=sharing

So this is a tricky one. I am looking to loop through the name in Sheet1 Column A, and also loop through the type in Column C. Then if Column A in Sheet1 matches the name of column A in Sheet2, AND the type is "pickup" I want to log the other information that is in Sheet 1 inside of Column C on Sheet 2. Log the things like "State", "Location", "City" next to the identical name in Sheet 2. I hope that makes sense.

I know I probably need to use a loop within a loop to do all this, but this is as far as I can get as I cannot figure out how to write the loop and then log the rows where the 2 names match.

function myFunction() {
   function pullDeliveryNotes()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var dataRange = sheet.getDataRange();
var dataRange2 = sheet2.getDataRange();
var rng = sheet.getRange(2,1, dataRange.getLastRow()-1,dataRange.getLastColumn());
var rng2 = sheet.getRange(2,3, dataRange.getLastRow()-1,dataRange.getLastColumn());
var rng3 = sheet2.getRange(2,1, dataRange2.getLastRow()-1,dataRange2.getLastColumn());
var rngA = rng.getValues().toString()
var rngB = rng2.getValues().toString()
var rngC = rng3.getValues().toString()
for(var i = 0; i < rng.length; i  ) {
  for (var x = 0; x < rng2.length; x  ) {
    for (var y = 0; y < rng3.length; y  ) {

if (rng[i][x][y].includes(rng3[i][x][y]) && rng2[i][x][y] === "pickUp") {
  Logger.log("We got it")
}

    }
  }
}

}
}

CodePudding user response:

Based on your problem statement.

Try this sample script:-

function checkValues() {
   
   const ss = SpreadsheetApp.getActiveSpreadsheet();
   const ssSource = ss.getSheetByName('Sheet1')
   const ssTarget = ss.getSheetByName('Sheet2')
   
   const sourceRange = ssSource.getDataRange().getValues().filter(r=> r[2] === 'Pickup'); // Filtering only pickup values
   const targetRange = ssTarget.getDataRange().getValues();
  
   for(var i = 0 ; i < sourceRange.length ; i  )
   {
        for(var j = 1 ; j < targetRange.length ; j  )
        {
          if(sourceRange[i][0] === targetRange[j][0]) // if name matches
          {
            ssTarget.getRange(`C${j 1}`).setValue(`${sourceRange[i][3]},${sourceRange[i][4]},${sourceRange[i][5]}`)  // set values in column C              
          }
        }
     
   } 
}
  • Related