在列中写入数据

时间:2017-05-22 23:54:49

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

使用下面的代码我试图将数据复制到新工作表但我希望它始终以A2开头。

我不希望数据不断地结束,我希望它总是从A2开始。此外,问题出现的地方是我在B2中有公式:N200所以数据不断尝试复制到最后。

最初代码看起来像这样:

if(data[n][0]){
     var dest = ss.getSheetByName(data[n][0].toString().replace(/ /g,''));//find the destination sheet
     Logger.log(data[n][0].toString().replace(/ /g,''))
     var destRange = dest.getRange(dest.getLastRow()+1,1);// define range
     master.getRange(selectedfirstRow+n,2,1,1).copyTo(destRange);// and make copy below last row
    }
  }

我意识到Var destRange正在定义从哪里开始输入数据。

if(data[n][0]){
     var dest = ss.getSheetByName('Sunday'.replace(/ /g,''));//find the destination sheet
     Logger.log(data[n][0].toString().replace(/ /g,''))
     var destRange = dest.getRange(2+1,1);// define range
     master.getRange(selectedfirstRow+n,2,1,1).copyTo(destRange);// and make copy below last row
    }
  }

如您所见,我将getRange更改为(2 + 1,1);每次运行函数时它都会进入下一行,但它只输入一个数据,而不是一致地进入下一行。

修改 而且我想我应该问一下,如何才能获得第一列中的最后一个空单元而不是整张表。我知道代码目前正在查看整个工作表的最后一行,如何才能找到第一列呢?

1 个答案:

答案 0 :(得分:0)

只获取第一列数据,然后找到数组中的第一个空元素。

获取2D数组(一个外部数组中的数组):

//Get the data from the first column only
columnOneData = dest.getRange(1,1,dest.getLastRow()).getValues();

需要将2D数组折叠为一维数组:

columnOneData = columnOneData.toString();//Convert the 2D array to a comma seperated string
columnOneData = columnOneData.split(",");//Convert the string to a 1D array

找到新数组中的第一个空元素:

firstRowWithEmptyCell = columnOneData.indexOf("") + 1;//Find the first empty element

放在一起:

function test() {
  var columnOneData,data,dest,destRange,firstRowWithEmptyCell,n,selectedfirstRow,ss;

  ss = SpreadsheetApp.getActive();

  if(data[n][0]){    
    dest = ss.getSheetByName('Sunday'.replace(/ /g,''));//find the destination sheet
    //Logger.log(data[n][0].toString().replace(/ /g,''))

    columnOneData = dest.getRange(1,1,dest.getLastRow()).getValues();//Get the data from the first column only
    columnOneData = columnOneData.toString();//Convert the 2D array to a comma seperated string
    columnOneData = columnOneData.split(",");//Convert the string to a 1D array

    Logger.log('columnOneData: ' + columnOneData)
    firstRowWithEmptyCell = columnOneData.indexOf("") + 1;//Find the first empty element
    Logger.log('firstRowWithEmptyCell: ' + firstRowWithEmptyCell)

    destRange = dest.getRange(2+1,1);// define range

    master.getRange(selectedfirstRow+n,2,firstRowWithEmptyCell,1).copyTo(destRange);// and make copy below last row
  }
}