How to set a value in the cells of the next column?

人盡茶涼 提交于 2020-05-17 05:25:58

问题


I have table with hundred of text entries.

I want to tag those entries according to the original text.

Eg:

TEXT (A)         TAG (B)
Facebook       Social Media
Instagram      Social Media
Stackoverflow  Good Site

I am using the code below.

But this only copies the column A into column B !!

 var sheet = SpreadsheetApp.getActiveSheet();
 var range = sheet.getRange('A2:A5');
 var data = range.getValues();
 var tag = sheet.getRange('B2:B5');

  for (var i = 0; i<data.length; i++) 
  {
      if(String(data[i][1]).match(/facebook|instagram/gi))
      {
        data([i][1]='Social Media');
      }
      if(String(data[i][1]).match(/Stack/gi))
      {
        data([i][1]='Good Site');
      }

 }
  tag.setValues(data); 
}

The current result :

TEXT (A)        TAG (B)
Facebook       Facebook    
Instagram      Instagram       
Stackoverflow  Stackoverflow  

回答1:


Try this:

function myfunction() { 
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange('A2:A5');
  var data = range.getValues();
  var tag = sheet.getRange('B2:B5'); 
  var vA= tag.getValues();
  for (var i = 0; i<data.length; i++) {
    if(String(data[i][0]).match(/facebook|instagram/gi)) {
      vA([i][0]='Social Media');
    }
    if(String(data[i][0]).match(/Stack/gi)) {
      vA([i][0]='Good Site');
    }   
  }
  tag.setValues(vA); 
}



回答2:


You are using the wrong indexes. The array that getValues() returns looks like this:

[ [ 'Facebook' ], [ 'Instagram' ], [ 'Stack Overflow' ], [ '' ] ]

So this code should work:

var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange('A2:A5');
var data = range.getValues();
var tag = sheet.getRange('B2:B5');

for (var i = 0; i < data.length; i++) {
    if (String(data[i][0]).match(/facebook|instagram/gi)) {
        data[i][0] = 'Social Media';
    }
    if (String(data[i][0]).match(/Stack/gi)) {
        data[i][0] = 'Good Site';
    }

}

tag.setValues(data);


来源:https://stackoverflow.com/questions/61297344/how-to-set-a-value-in-the-cells-of-the-next-column

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