仅选择Google电子表格中的行,其中使用Google Apps脚本将某列中的值或公式设置为空

时间:2012-06-23 11:06:51

标签: google-apps-script google-sheets

我有一个Google电子表格,我在尝试找出选择多行所需的代码时遇到了很大困难。

我想要选择的唯一行是其中一列中具有值公式的行(比如说B列)。

无法按列排序工作表,只选择前x个值。

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

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

2 个答案:

答案 0 :(得分:3)

这应该做你想要的......也许它需要一些调试因为我没有测试它因为我不确定你真正想要的东西; - )

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
          }
        }

答案 1 :(得分:0)

在这些方面尝试一下 - 这段代码没有经过测试,但会给你一个公平的想法

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
  }
}