如何循环google电子表格列值并在B列中设置结果?

时间:2015-10-11 01:06:05

标签: loops google-apps-script google-sheets

我在A列中有一个网址列表,我希望循环显示此列A并将每个网址的状态代码设置为B列。我尝试了此代码,但我一直在未找到范围在脚本编辑器窗口?我知道我必须将行的值添加到列B的名称,但我不断收到此错误。任何人都告诉我如何解决此错误。提前感谢。

function getStatus() {

    var queryString = Math.random();

  var ss = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = ss.getSheetByName("Sheet1"),
      urls = sheet.getRange("A2:A").getValues(),

      row, len


  for (row = 0, len = urls.length; row < len; row++) {
    if (urls[row] != '') {

        var cellFunction1 = '=HTTPResponse("' + urls[row] + '?' + queryString + '")';
  SpreadsheetApp.getActiveSheet().getRange('"B"+row+').setValue(cellFunction1);

     } 
  }

  }

function HTTPResponse( uri )
{
 var response_code ;
try {
 response_code = UrlFetchApp .fetch( uri ) .getResponseCode() .toString() ;
 }
catch( error ) {
 response_code = error .toString() .match( / returned code (\d\d\d)\./ )[1] ;
 }
finally {
 return response_code ;
 }
}

1 个答案:

答案 0 :(得分:1)

可能有更好(也更优雅)的方法,但至少这似乎有效:

 function getStatus() {    

  var queryString = Math.random();    

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1");

  var lastRow = sheet.getLastRow();
  var lastColumn = sheet.getLastColumn(); 
  var dataRange = sheet.getRange(2, 1, lastRow -1, lastColumn);
  var data = dataRange.getValues();
  var row = 0;
  var len = data.length;


  for (row; row < len; row++) {
    if (data[row] != '') {    

        var cellFunction1 = '=HTTPResponse("' + data[row][0] + '?' + queryString + '")';
        // change the following line, last number for another column
        var cell = sheet.getRange(row+2, 2);
        cell.setValue(cellFunction1);

     } 
  }    

  }    

function HTTPResponse( uri )
{
 var response_code ;
try {
 response_code = UrlFetchApp .fetch( uri ) .getResponseCode() .toString() ;
 }
catch( error ) {
 response_code = error .toString() .match( / returned code (\d\d\d)\./ )[1] ;
 }
finally {
 return response_code ;
 }
}

也许你可以从这里开始改进它。 screenshot spreadsheet columns