How to set values in new column with validation from a Named Range?

霸气de小男生 提交于 2020-04-30 08:47:38

问题


Following a previous question

I want to classify text entries by adding a tag in the next column.

I could do it using regex but it will take too much time writing all conditions like :

 if(String(data[i][0]).match(/acme|brooshire|dillons|target|heb|costco/gi))
      {
         labValues[i][0]='Supermarket';
    }

Instead I created a named list with all stores names (in another sheet).

If an entry matches a term in the list, the next column is set to "Supermarket".

I am using this script below... No bugs but nothing happens when executed !

 function tagStore() {
 var sheet = SpreadsheetApp.getActiveSheet();
 var range = sheet.getRange('A2:A655')
 var store = range.getValues();
 var tag = sheet.getRange('B2:B655');
 var tagvalues= tag.getValues();
 var storeList= SpreadsheetApp.getActive().getRangeByName("store_list");

  for (var i = 0; i<store.length; i++) 
  {
      if(String(store[i][0]).match(storeList))
      {
         tagvalues[i][0]='Supermarket';
      }
      }
  tag.setValues(tagvalues);  
}

Edit:

It is important to use a Regex as the "store" Values are not exactly the same as the "store_list".

Store Values : ["Acme Store", "HEB PLaza", "Dillons Group"...]

Store_List : [acme, heb, dillons...]

回答1:


Instead of trying to go with the regEx approach there is a more straightforward approach by retrieving the range as a list.

// For a Column
var storeList = SpreadsheetApp.getActive().getRangeByName("store_list").getValues().map(function(r){return r[0];});

// For a Row
var storeList = SpreadsheetApp.getActive().getRangeByName("store_list").getValues()[0];

And then look if the values you are looking for are in this list with indexOf().

Try this:

function tagStore() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange('A2:A655')
  var store = range.getValues();
  var tag = sheet.getRange('B2:B655');
  var tagvalues= tag.getValues();
  var storeList= SpreadsheetApp.getActive().getRangeByName("store_list").getValues().map(function(r){return r[0];});//if it's a column
  //var storeList=SpreadsheetApp.getActive().getRangeByName("store_list").getValues()[0];//if it's a row
  for (var i=0;i<store.length; i++) {
    if(storeList.indexOf(store[i][0])!=-1) {
      tagvalues[i][0]='Supermarket';
    }
  }
  tag.setValues(tagvalues);  
}


来源:https://stackoverflow.com/questions/61305487/how-to-set-values-in-new-column-with-validation-from-a-named-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!