【问题标题】:Select only the rows from a Google Spreadsheet where values or formulas in a certain column are not empty using Google Apps Scripts使用 Google Apps 脚本仅从 Google 电子表格中选择特定列中的值或公式不为空的行
【发布时间】:2012-06-25 12:11:53
【问题描述】:

我有一个 Google 电子表格,但我很难计算出选择多行所需的代码。

我要选择的唯一行是在其中一列(假设是 B 列)中具有值 公式的行。

不能按列排序工作表,只选择前 x 值。

我想我需要遍历工作表中的每一行并确定 B 列是否为空,但我不知道如何执行此操作或如何检查单元格是否包含值或公式。如果它包含一个公式,那么它必须优先于值保留。

如何使用 Google Apps 脚本仅从 Google 电子表格中选择某一列中的值或公式不为空的行?

【问题讨论】:

  • “选择行”是什么意思?你想对他们做什么?据我所知,仍然没有任何方法(脚本或其他方式)可以选择 GSheets 中的“激活”非连续单元格。

标签: google-apps-script google-sheets


【解决方案1】:

在这些行上尝试一些东西 - 此代码未经测试,但会给你一个公平的想法

var sheet = // get sheet ; 
var data = sheet.getDataRange().getValues(); 
for ( var i = 0; i < data.length ; i++){
  if (data[i][1] != ''){  // Column B is at index 1
    // Do whatever you want
  }
}

【讨论】:

  • 谢谢斯里克。 getValues() 不只获取值吗?我知道还有 getFormulas() 但我看不到一个组合。
  • 你是对的,你应该使用2个条件,一个getValues和一个getFormulas
  • 您想将这些行复制到另一个工作表吗?
【解决方案2】:

这应该可以满足您的需求...也许它需要一些调试,因为我没有测试它,因为我不确定您真正想要什么;-)

function copynotempty(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = SpreadsheetApp.setActiveSheet(ss.getSheets()[0])
  var col = 1 ; // choose the column you want to check: 0 = col A, 1= col B ...
  var range = sh.getDataRange();
  var values=range.getValues();// data is a 2D array, index0 = col A
  var formulas=range.getFormulas();// data is a 2D array, index0 = col A
  var target=new Array();// this is a new array to collect data
   for(n=0;n<range.getHeight();++n){
     if (values[n][col]!=''|| formulas[n][col]!=''){ ; 
        for (cc=0;cc<range.getWidth();++cc){
                if (formulas[n][cc]!=''){target[n][cc]=formulas[n][cc]}else{target[n][cc]=values[n][cc]}
    // if the cell has a formula copy it or else copy the value, do that for the whole row
// (this also defines and apply the 'priority' you mentioned in your question, I wasn't sure if it should apply to the whole row or only on column B)
                }
              }
            }
            if(target.length>0){// if there is something to copy
          var sh2=SpreadsheetApp.setActiveSheet(ss.getSheets()[1]); //second sheet of your spreadsheet
          sh2.getRange(1,1,target.length,target[0].length).setValues();// paste the selected values in the 2cond sheet
          }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-12
    • 2017-03-27
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多