I need to copy data from 3 sheets to another maste

2019-06-10 04:46发布

问题:

I have written a code for this but getting an error

The coordinates or dimensions of the range are invalid. (line 44)

Code:

function updateMaster() {
var repArray  = new Array();
 var ss        = SpreadsheetApp.getActiveSpreadsheet();
 var allSheets = ss.getSheets();
 // build array of all sheets
 for (i in allSheets) {                              
   if ((allSheets[i].getName()).match(/.*?\-Rep$/))
      {repArray.push(allSheets[i].getName());}
 }

 // store all sheets in array
 var sheetArray = [];   
 // loop through all rep sheets                             
 for (var j in repArray) {       
   // get each sheet                    
   var tempSheet  = ss.getSheetByName(repArray[j]);  
       // get sheet data
   var dataRange  = tempSheet.getDataRange().getValues(); 
   // remove the first header row
   dataRange.splice(parseInt(0), 1);                 
       // append sheet data to array
   var sheetArray = sheetArray.concat(dataRange);    
 }

 // Time to update the master sheet
 var mSheet    = ss.getSheetByName("summary");        
 // save top header row
 var headerRow = mSheet.getRange(1,1,1,12).getValues(); 
 // clear the whole sheet
 mSheet.clear({contentsOnly:true});                 
 // put back the header row 
 mSheet.getRange(1, 1, 1, 12).setValues(headerRow); 

This is where i am getting error while writing to master sheet:

 // write to the Master sheet via the array 
 mSheet.getRange(2, 1, sheetArray.length, 12).setValues(sheetArray);
  // force spreadsheet updates
 SpreadsheetApp.flush();                   
 // pause (1,000 milliseconds = 1 second)          
 Utilities.sleep("200");                             

 // delete empty rows at bottom
 var last = mSheet.getLastRow();                     
 var max  = mSheet.getMaxRows();
 if (last !== max) {mSheet.deleteRows(last+1,max-last);}

}

I am not able to figure out the error. Any help is appreciated. I am new to to this need help asap.

回答1:

You need a sheet with "Rep" inside the name.

"The first array stores all the Sales Rep sheets. Since some sheets could be something other than Sales Rep sheets, the script stores sheets only if the sheet name has a “-Rep” suffix (e.g. “JohnDoe-Rep”)"

code source: http://blog.ditoweb.com/2012/01/consolidate-spreadsheet-sheets-with.html

That's why it's not working.



回答2:

mSheet.getRange(2, 1, sheetArray.length, 12).setValues(sheetArray)

I faced the same issue and solved it by following the "Rep" solution. Then I ran into another problem and realized that my number of columns was different... so just go back in and change the no 12 to the number of rows you have in your sheet.

Also try to keep the format of the all sheets the same.

Rename the sheet where you would like the data to combine