簡體   English   中英

如何從特定列中獲取具有值的最后一行,該列的行數與其他列的值不同

[英]How to get the last row that has a value from a specific column which don't have the same amount of rows with values as other columns

一種
1個 一種 是的
2個
3個 C
4個 是的
5個
6個 F
7
8個

什么腳本可用於查找“B”列的最后一行 ID? 我不能使用“getLastRow()”,因為它會返回“A”列的 ID(在這種情況下,因為 A 有更多行的值)我不能使用“filter(String).length”,因為“ B”列有多個空單元格

應該返回的正確單元格是 B4

您可以嘗試僅對 B 列值進行反向搜索。

這個想法是獲取范圍值,在 memory 中使用它們,然后找到最后一個填充單元格的索引。

使用此索引,您可以從Range實例中獲取 A1 表示法。

示例代碼:

function findLastPopulatedA1Ref(){
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var bcolRange = ss.getRange("B2:B30"); //Getting B column range, arbitrary size. Modify it accordingly
    var bcolVals = bcolRange.getValues(); 

    var i; //declaring the index outside loop to reuse it later
    for (i = bcolVals.length - 1; i >= 0; i--) { //reversing the loop (end to start) to find the first non-empty cell
        if(bcolVals[i] != ""){
          console.log(`${i}: bcol[i] == ${bcolVals[i]}`); //(optional) Just for debugging purposes
          break; // Forcing the end of the for loop, thus keeping the desired index value in i
        }
    }
    if (i == -1){
      console.log("Warning: B column is empty"); //(optional) Just for debugging purposes
      return null; //B Column is empty
    }
    var result = bcolRange.getCell(i+1, 1).getA1Notation(); //getCell starts at (1,1) and js arrays starts at 0. That's the reason to add 1.
    console.log(result); //(optional) Just for debugging purposes
    return result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM