Google Apps脚本:获取范围值,编辑值并将值设置为范围

时间:2015-03-03 10:41:05

标签: google-apps-script google-sheets

我想构建一个菜单功能来编辑google工作表中的选定值:

function fDoSomethingWithRange(){
  //var theSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();

  var theSheet = SpreadsheetApp.getActiveSheet();
  var theRange = theSheet.getActiveRange();
  var theValues = theRange.getValues();
  var theArray = new Array(theRange.getHeight());
  //theSpreadsheet.toast(theValues);

  for (var i = 0;i<theRange.getHeight();i++){
    theArray[i]=new Array(theRange.getWidth());
    };

  for (var h=0;h<theRange.getHeight();h++){  
    for (var w=0;w<theRange.getWidth();w++){

      var i = h + (w * theRange.getHeight());
      theArray[h][w] = parseInt(theValues[i]) * 2; // just an example return double values
    };
  };
  theRange.setValues(theArray);
};

我在返回阵列时遇到困难;第二栏是空的,我不知道为什么。任何人

感谢, 阿尔维德

1 个答案:

答案 0 :(得分:3)

好的,我自己找到了......最后: - )

getValues()获取一个二维数组。我被toast消息所欺骗,它只显示一行值,表明getValues()获得了一维数组。

function fDoSomethingWithRange(){
  //var theSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();

  var theSheet = SpreadsheetApp.getActiveSheet();
  var theRange = theSheet.getActiveRange();
  var theValues = theRange.getValues();
  var theArray = new Array(theRange.getHeight());
  //theSpreadsheet.toast(theValues);

  for (var i = 0;i<theRange.getHeight();i++){
    theArray[i]=new Array(theRange.getWidth());
    };

  for (var h=0;h<theRange.getHeight();h++){  
    for (var w=0;w<theRange.getWidth();w++){

      var i = h + (w * theRange.getHeight());
      theArray[h][w] = parseInt(theValues[h][w]) * 2; // just an example return double values
    };
  };
  theRange.setValues(theArray);
};