I have a list of data on Sheet1 columns A-N, and a list of updates on Sheet2, columns A-N. I have a code that imports data to Sheet2, and I would like to add to my code a similar function to VLOOKUP. In essence, I want the code to check the values in Column C on Sheet1 within my list of updated data in Column B on Sheet2. If it finds a match, I want the code to copy/paste the updates in the corresponding columns for that found value in that row in Sheet 1. If it doesn't find a match, I want it to copy/paste the whole row from Sheet2 to the bottom of the list in Sheet1.
In my example file, I have two yellow cells on Sheet 2 highlighted to show what I want the code to find. Essentially, the script should look up the value in Column C on Sheet 1, search for the same value in Column B on Sheet2, and if it finds it, to pull in the updated cells and copy/paste to the corresponding cell on Sheet1. I also have a new set of data in row 5 of Sheet 2, and the code should copy/paste this whole row to Sheet 1.
I have the start of a code, but I know it needs much more:
function TEST() {
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var last=ss.getLastRow();
var data=sh.getRange(1,1,last,2).getValues();
for(nn=0;nn<data.length;++nn){
if (data[nn][1]==valB){break} ;
//Copy/pastes updates if a value is found
//Copy/pastes whole row if value isn't found
}
}
Best Answer
You have search values in a given column on a given sheet. You want to use those values to search for matching values in a different given column on a different sheet. If a match is found, then you want to update any differences from the search row to the matched row. If a difference is not found, you want to append the entire search row to the un-matched sheet.
Consider the following script:
Lookup sheet: Before
Lookup sheet: After
PROCESSING LOGIC
Get the data for both sheets
var lookupRange = lookup.getRange(lookupStartRow,1,lookupRows,colNum);
,var lookupData = lookupRange.getValues();
var searchData = search.getRange(searchStartRow,1,searchRows,colNum).getValues();
Create 1D arrays for the search values on both sheets by using the Javascript
map
method (ref)var searchSearchRange = searchData.map(function(e){return e[(+searchSearchCol-1)];});
var lookupSearchRange = lookupData.map(function(e){return e[(+lookupSearchCol-1)];});
Using the Javascript
indexOf
method (ref), loop through the search values using the 1D array values to find a matching term in the lookup rangevar result = lookupSearchRange.indexOf(searchSearchRange[v]);
result
will be either:if there is a match (
if (result != -1){
), thenlookupData[result][(+lookupSearchCol+i)] = searchData[v][(+searchSearchCol+i)]
result
) and the search row number (v
) could have different row index values, but these variables maintain consistency from sheet to sheet.lookupRange.setValues(lookupData);
if no match, then append the entire row
searchData[v].splice(0, 0, " ");
lookup.appendRow(searchData[v]);