简体   繁体   中英

Copy row if value exists in both sheet 1 and sheet 2 and paste it to sheet 3. Google Sheets. Google Apps Script

I am needing help on a part of my script. I have a large imported list of data on sheet one, on one column there are a list of phone numbers. I want to compare that column of phone numbers to a set list of numbers in sheet 2. If there are matching numbers, copy the entire row from sheet 1 to sheet 3. Here is what i have so far.

function copyRowtoSheet3() { 
  var s1 = SpreadsheetApp.openById("1Aw11LiKzyezfrTQIuTsJPhUFtz8RPqLCc8FlIiy0ZlE").getSheetByName('Sheet1');
  var s2 = SpreadsheetApp.openById("1Aw11LiKzyezfrTQIuTsJPhUFtz8RPqLCc8FlIiy0ZlE").getSheetByName('Sheet2'); 
  var s3 = SpreadsheetApp.openById("1Aw11LiKzyezfrTQIuTsJPhUFtz8RPqLCc8FlIiy0ZlE").getSheetByName('Sheet3'); 
  var values1 = s1.getDataRange().getValues();
  var values2 = s2.getDataRange().getValues();
  var resultArray = [];
  for(var n=0; n < values1.length ; n++){
    var keep = false;
    for(var p=0; p < values2.length ; p++){
      Logger.log(values1[n][0]+' =? '+values2[p][0]);
      if( values1[n][0] == values2[p][0] && values1[n][1] == values2[p][1]){
        resultArray.push(values1[n]);
        Logger.log('true');
        //break ;
      }
    }
  }  
  s3.getRange(+1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}

What i have now kindof works, however its not perfect as it only seems to copy the number from sheet one, not the entire row, or doesnt work at all. I get this error a lot, but not all the time. TypeError: Cannot read property 'length' of undefined (line 19, file "Code") Not quite sure what im doing wrong. Any advice here would be helpful. For reference, Here is what my sheets look like and what im wanting this code to do.

Sheet1
Name      Phone Number  
John      2142354696
Virge     2345678901
Jason     2412305968
Tiffany   1304086932

Sheet2
Phone Numbers
2142354696
2412305968


Sheet3
John      2142354696
Jason     2412305968

It works only when the entire row is similar, because in If you are comparing the value of the two columns of the two worksheets.

If in sheet1 the phone number is in the second column and in sheet2 the number is in the first column, the correct thing would be to compare sheet1 [row N] [column 1] == sheet2 [row N] [column 0]. This is the only comparison to be made, only the cells of interest.

Keep all your code and just change the If line to:

if( values1[n][1] == values2[p][0] ){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM