如何使用getRange在Google表格中查找最后一行

时间:2018-11-03 08:56:18

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

我正在使用以下脚本查找和替换文本。唯一的问题是在该行中:

var range = sheet.getRange("D2:D2000");

它在设置为2000的最后一行之后创建新行。我需要找到最后一行,然后更改此行代码。我迷路了:(

我的总脚本如下:

function runReplaceInSheet() {

var spreadsheet = SpreadsheetApp.openById("1NK-pmvrJoSqKSgx2zRCAcRKGjk8SiiSsfwwerhfdM1SE"); // UPDATE ID
var sheet = SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]);     // UPDATE number in square brackets


var range = sheet.getRange("D2:D2000");


//  get the current data range values as an array
//  Lesser calls to access the sheet, lower overhead 
var startRow = 2; // First row of data to process
var numRows = 2; // UPDATE number of rows to process
// Fetch the range of cells 
var dataRange = sheet.getRange(startRow, 4, numRows, 1) // Numbers of rows to process
    // Fetch values for each row in the Range
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var v = row[3]; // edit: don't need this
    var values = range.getValues();  

    // Replace Names

    replaceInSheet(values, '1', 'Active');
    replaceInSheet(values, '0', 'Inctive');

    //write the updated values to the sheet, again less call;less overhead
    range.setValues(values);        
}
}

function replaceInSheet(values, to_replace, replace_with) {

//loop over the rows in the array
for (var row in values) {

    //use Array.map to execute a replace call on each of the cells in the row.
    var replaced_values = values[row].map(function(original_value) {
        return original_value.toString().replace(to_replace, replace_with);
    });

    //replace the original row values with the replaced values
    values[row] = replaced_values;


}
}

1 个答案:

答案 0 :(得分:0)

您可以使用sheet.getDataRange()返回一个范围,该范围描述其中包含一些数据的图纸区域。

如果您只想要D2:d列,则可以这样做

var range = sheet.getDataRange();
range = range.offset (1,3,range.getNumRows()-1,1);

或者您可以像这样将数据放入一维数组

var values = sheet.getDataRange().getValues().slice(1)
.map (function (d) {
    return d[3];
});

有很多方法。