将所有列移动到列表仅粘贴一次

时间:2018-01-26 14:43:48

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

我正在尝试将列表中的所有列复制到新的空白表中,在第1列上开始回发

我想只回发一次而不是分别为每一列

我收到错误 TypeError: Cannot find function getValues in object Range,Range,Range

var sV = sourceRange.getValues();

感谢任何帮助,谢谢

function arrMoveCols2_n(){

   arrMoveCols2("Elements","Z", ["Id", "Label", "Email"]);  

}


function arrMoveCols2(SshtName, TshtName, sArr){
var sSheet =  SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SshtName);
 var sLC = sSheet.getLastColumn();
 var sLR = sSheet.getLastRow();

 var tSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(TshtName);
  var tRange = tSheet.getRange(1, 1, sLR, sArr.length);

  var sNew = [];
  var sourceRange = [];

  for (var i = 0; i < sArr.length; i++){
     //Headers to Letters
     sNew[i] = HTL(SshtName, sArr[i]);

     //Get the Source Range of Column to be Moved under
     sourceRange[i] = sSheet.getRange(sNew[i] + '1:' + sNew[i] +sLR);
  };

  var sV = sourceRange.getValues();

  tRange.setValues(sV);
}

辅助功能

//Header to Letter
function HTL(shtName,cheader){
  var headers = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(shtName).getDataRange().getValues().shift();
  var colindex = headers.indexOf(cheader);
      cLetter = NTL(colindex +1);
      return cLetter;
}

1 个答案:

答案 0 :(得分:1)

您在此处定义范围数组:

sourceRange[i] = sSheet.getRange(sNew[i] + '1:' + sNew[i] +sLR)

因此,您必须单独获取每个范围的值,并将其附加到您的sV数组中,如下所示:

 var sV = []
    for (var a in sourceRange){
     var tempData = sourceRange[a].getValues()
      for (var b in tempData){
       if(a == 0)
         sv[b] = []
       sv[b].push(tempData[b][0]) //If you have more then one column of data
                                  //You will have to include one more loop 
      }
    }

您的最终代码:

function arrMoveCols2(SshtName, TshtName, sArr){
 var sSheet =  SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SshtName);
 var sLC = sSheet.getLastColumn();
 var sLR = sSheet.getLastRow();

 var tSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(TshtName);
 var tRange = tSheet.getRange(1, 1, sLR, sArr.length);

  var sNew = [];
  var sourceRange = [];

  for (var i = 0; i < sArr.length; i++){
     //Headers to Letters
     sNew[i] = HTL(SshtName, sArr[i]);

     //Get the Source Range of Column to be Moved under
     sourceRange[i] = sSheet.getRange(sNew[i] + '1:' + sNew[i] +sLR);
  };

  var sV = []
        for (var a in sourceRange){
         var tempData = sourceRange[a].getValues()
          for (var b in tempData){
           if(a == 0)
             sv[b] = []
           sv[b].push(tempData[b][0])
          }
        }
  tRange.setValues(sV);
}