0

あるシートから別のシートに列をインポートするアプリを作成しています。.getLastRow メソッドはシート全体にのみ適用されますが、列の最後の行を取得するために使用することはできません。この機能を要求する未解決の問題があります。

Google Script Examples の 2D 配列ライブラリの助けを借りて何かを書きました: https://sites.google.com/site/scriptsexamples/custom-methods/2d-arrays-library

特定の列の最後の行を見つける作業バージョンを入手しましたが、かなり効率が悪いと思います。

function readRows() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var numRows = sheet.getLastRow();
  var numColumns = sheet.getLastColumn();
  var data = sheet.getRange(1, 1, numRows, numColumns).getValues();

//Get the Headers, Search for a value of the headers and index  
var headerArray = sheet.getRange(1, 1, 1, numColumns).getValues();
var flip = ArrayLib.transpose(headerArray)
var search = "Greens";
var whereGreen = ArrayLib.indexOf(flip, 0, search);


//Get the value of the column with matching headers, and looks up Column length. 
 var values = sheet.getRange(1, whereGreen +1, numRows, 1).getValues();

//finds last value, makes string
for(; values[numRows - 1] == "" && numRows > 0; numRows--) {}
   var lastValue = values[numRows - 1].toString();

//Indexes where the string is, which gives the value -1 of the last row in column.   
var lastRowCol = ArrayLib.indexOf(values, 0, lastValue);

 Logger.log(lastRowCol +1);

 }

合理化されたバージョンに到達するのを手伝ってくれる人はいますか? JavaScriptでできると確信していますが、その分野の知識はかなり不足しています。

4

2 に答える 2

2

スプレッドシート サービスの呼び出し回数を減らすことで、コードをより効率的にすることができます。次のコードははるかに高速です。

function readRows() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var data = sheet.getDataRange().getValues();
  var numRows = data.length;

//Get the Headers, Search for a value of the headers and index  
  var headerRow = data[0];
  var search = "Greens";
  var whereGreen = headerRow.indexOf(search);

//finds last value, makes string
  while( data[numRows - 1][whereGreen] == "" && numRows > 0 ) {
    numRows--;
  }
  var lastValue = data[numRows - 1][whereGreen].toString();

  Logger.log( 'Last row: '+ numRows );
  Logger.log( 'Last value: '+ lastValue );

// Not clear what this does, what more information is needed?
//Indexes where the string is, which gives the value -1 of the last row in column.   
//var lastRowCol = ArrayLib.indexOf(values, 0, lastValue);
//  Logger.log(lastRowCol +1);
}

for ループを while ループに置き換えましたが、効率に大きな違いはなく、もう少し読みやすくなっています。

于 2013-02-12T20:13:45.907 に答える
1

効率という点では、私の意見では、これは効率に近づくのとほぼ同じです。よりクリーンなソリューションに関しては、今のところ考えられないようです。何か思いついたら更新します。

于 2013-02-11T20:16:26.477 に答える