I'm writing a script to loop through each sheet in one spreadsheet and copy data from specific cells into a corresponding sheet on another spreadsheet. I am getting an error on line 18 of the below code, however, stating that it can't call the getLastRow method of null. I used a couple of Logger.log lines to check my variables and see that targetSheet is coming back as null. Any advice on what I've got wrong?
//Export each sheet's daily data to another sheet *Test Version*
function exportReports() {
var sourceSS = SpreadsheetApp.getActiveSpreadsheet();
//Open Back Production Record *Test Version*
var targetSS = SpreadsheetApp.openById("1ZJKZi-UXvqyGXW9V7KVx8whxulZmx0HXt7rmgIJpUY4");
var allSourceSheets = sourceSS.getSheets();
//For-Loop to loop through hourly production sheets, running the move data for-loop on each
for(var s in allSourceSheets){
var loopSheet = allSourceSheets[s];
var loopSheetName = loopSheet.getSheetName();
var targetSheet = targetSS.getSheetByName(loopSheetName);
Logger.log(s);
Logger.log(loopSheet);
Logger.log(targetSheet);
Logger.log(loopSheetName);
var targetRow = targetSheet.getLastRow()+1;
var currentDate = Utilities.formatDate(new Date(), "GMT-5", "MM/dd/yy");
targetSheet.getRange(targetRow, 1).setValue(currentDate);
//For-Loop to move data from source to target
for(var i=6;i<=10;i++){
var sourceRange = sourceSheet.getRange(i, 2);
var targetRange = targetSheet.getRange(targetRow, i-4);
var holder = sourceRange.getValue();
targetRange.setValue(holder);
}
}
}
Per the documentation on getSheetByName, if the target sheet name does not exist, then you get null as a return value.
getSheetByName(name)
Returns a sheet with the given name.
If multiple sheets have the same name, the leftmost one is returned. Returns null if there is no sheet with the given name.
So, the desired sheet with name specified by loopSheetName does not exist in the target workbook. Perhaps someone has created a new sheet, or renamed an existing sheet in the source workbook.
You haven't asked about it, but you can improve the performance of your copy code as well, by reading the inputs as a multi-row range array, creating a row array to hold the results, and writing that once:
var sourceData = sourceSheet.getRange(6, 2, 5, 1).getValues(); // (6,2) through (10, 2)
var output = [];
// Transpose row array to column array (could use other functions, but this is easier to understand)
for(var i = 0; i < sourceData.length; ++i) { output.push(sourceData[i][0]); }
targetSheet.getRange(targetRow, 2, 1, output.length).setValues([output]); // i0 = 6 -> 6 - 4 = 2
I am attempting to write a script that on form submit will send two sets of data to two different spreadsheets. The data is derived from one form. It is supposed to copy the most recent entry and then hide the row to prevent duplication. I am finding that on some occasions it is not hiding the last row and multiple copies are being copied. I realize my script is probably not the most efficient, for example, I could not get a range to work!
The sleep utilities were inserted as I thought there may have been a delay in the writing of the form's input to the spreadsheet and the script was running before this was complete.
The script is attached to the form which writes to a Form Responses sheet, this is then split to a company spreadsheet and a customer spreadsheet. Well that is the intention anyway!
function copyRow(){
Utilities.sleep(2000)
var ss = SpreadsheetApp.openById('1_pnsvWtqB4CUivQZE65nFR0AG9zTOgqBVSlPZW4YCUQ'); //Source Form Input
var sheet = ss.getSheetByName('Responses');
var lastrow = ss.getLastRow();
var rowIdx = sheet.getLastRow();
var rowValues = sheet.getRange(lastrow,1,1,74).getValues();
Logger.log(rowValues);
Utilities.sleep(5000)
var destValues = []; //Data to AUSJET
destValues.push(rowValues[0][0],rowValues[0][1],rowValues[0][2],rowValues[0][3],rowValues[0][4],rowValues[0][5],rowValues[0][6],rowValues[0][7]
,rowValues[0][8],rowValues[0][9],rowValues[0][10],rowValues[0][11],rowValues[0][12],rowValues[0][13],rowValues[0][14],rowValues[0][15]
,rowValues[0][16],rowValues[0][17],rowValues[0][18],rowValues[0][19],rowValues[0][20],rowValues[0][21],rowValues[0][22],rowValues[0][23]
,rowValues[0][24],rowValues[0][25],rowValues[0][26],rowValues[0][27],rowValues[0][28],rowValues[0][29],rowValues[0][30],rowValues[0][31]
,rowValues[0][32],rowValues[0][33],rowValues[0][34],rowValues[0][35],rowValues[0][36],rowValues[0][37],rowValues[0][38],rowValues[0][39]
,rowValues[0][40],rowValues[0][41],rowValues[0][42],rowValues[0][43],rowValues[0][44],rowValues[0][45],rowValues[0][46],rowValues[0][47]
,rowValues[0][48],rowValues[0][49],rowValues[0][50],rowValues[0][51],rowValues[0][52],rowValues[0][53],rowValues[0][54],rowValues[0][55]
,rowValues[0][56],rowValues[0][57],rowValues[0][58],rowValues[0][59],rowValues[0][60],rowValues[0][61],rowValues[0][62],rowValues[0][63]
,rowValues[0][64],rowValues[0][65],rowValues[0][66],rowValues[0][67],rowValues[0][68],rowValues[0][69],rowValues[0][70],rowValues[0][71]
,rowValues[0][73],rowValues[0][74]);
// copy data from col A to col BU
var dest = SpreadsheetApp.openById('1KQ43DJsJY0RpSnFHDcVfgAWLRfLKE6OD28CFkbjpJoU').getSheetByName('Form Responses');[1];
dest.getRange(dest.getLastRow()+1,1,1,destValues.length).setValues([destValues]);
var destValues = []; //DATA to CONCATENATOR
destValues.push(rowValues[0][0],rowValues[0][1],rowValues[0][2],rowValues[0][3],rowValues[0][4],rowValues[0][5],rowValues[0][6],rowValues[0][7]
,rowValues[0][8],rowValues[0][9],rowValues[0][10],rowValues[0][11],rowValues[0][12],rowValues[0][13],rowValues[0][14],rowValues[0][15]
,rowValues[0][16],rowValues[0][17],rowValues[0][18],rowValues[0][19],rowValues[0][20],rowValues[0][21],rowValues[0][22],rowValues[0][23]
,rowValues[0][24],rowValues[0][25],rowValues[0][26],rowValues[0][27],rowValues[0][28],rowValues[0][29],rowValues[0][30],rowValues[0][31]
,rowValues[0][32],rowValues[0][33],rowValues[0][34],rowValues[0][35],rowValues[0][36],rowValues[0][37],rowValues[0][38],rowValues[0][39]
,rowValues[0][40],rowValues[0][41],rowValues[0][42],rowValues[0][43],rowValues[0][44],rowValues[0][45],rowValues[0][46],rowValues[0][47]
,rowValues[0][48],rowValues[0][49],rowValues[0][50],rowValues[0][51],rowValues[0][52],rowValues[0][53],rowValues[0][54],rowValues[0][55]
,rowValues[0][56],rowValues[0][57],rowValues[0][58],rowValues[0][59]);
// copy data from col A to col BH
var dest = SpreadsheetApp.openById('1qB4OnKF3-OXFR1kR3jewHgYeslLdmIiE3maQNx0MPbk').getSheetByName('ROAMES');[1];//
dest.getRange(dest.getLastRow()+1,1,1,destValues.length).setValues([destValues]);
Utilities.sleep(2000)
sheet.hideRows(lastrow)
I am assuming, that as the data is coming from the form so the first column will be 'Timestamp'.
So, I have copied the last row from the source spreadsheet and then compared the value of column A of this last row with the value of column A of the last row of Destination sheet, if both matches then I haven't copied the data...
Only thing that may cause an issue here is if two or more responses are submitted exactly at a same time
Try the following code:
function copyRow(){
Utilities.sleep(2000);
var ss = SpreadsheetApp.openById('1_pnsvWtqB4CUivQZE65nFR0AG9zTOgqBVSlPZW4YCUQ');
var sheet = ss.getSheetByName('Responses');
var lastrow = sheet.getLastRow();
var destValues = sheet.getRange('A'+lastrow+':BU'+lastrow).getValues();
var dest = SpreadsheetApp.openById('1KQ43DJsJY0RpSnFHDcVfgAWLRfLKE6OD28CFkbjpJoU').getSheetByName('Form Responses')
if( dest.getRange(dest.getLastRow(), 1,1,1).getValue().toString() != destValues[0][0].toString() )
dest.getRange(dest.getLastRow()+1,1,1,destValues[0].length).setValues(destValues);
var destValues = sheet.getRange('A'+lastrow+':BH'+lastrow).getValues();
var dest = SpreadsheetApp.openById('1qB4OnKF3-OXFR1kR3jewHgYeslLdmIiE3maQNx0MPbk').getSheetByName('ROAMES')
if( dest.getRange(dest.getLastRow(), 1,1,1).getValue().toString() != destValues[0][0].toString() )
dest.getRange(dest.getLastRow()+1,1,1,destValues[0].length).setValues(destValues);
};
I have been searching for a way to copy certain cells from a row and paste them into another spreadsheet, but all I can seem to find are ways to do that just from sheet to sheet within one spreadsheet or questions that deal with code way above my head. I'm just now learning to code in Google Spreadsheets and I can't seem to get it right. Here is my code for now, I'm working on just copying one cell first and after I can do that I'll get a loop to iterate through the row and pick the cells I want to copy.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var master = SpreadsheetApp.openById('0AgcCWQn-aoI1dFpLVE4tSENwcThrYnlMUzhuRmdWU2c');
var target = SpreadsheetApp.openById('0AgcCWQn-aoI1dF96X2dBT2dVVFZ2SU1NRWdYTDJhT2c');
var master_sheet = master.getSheetByName("Steve2");
var target_sheet = target.getSheetByName("Corbin1");
var master_range = master_sheet.getRange("A1");
var target_range = target_sheet.getRange("A1");
master_range.copyTo(target_range);
Right now it is giving me an error saying that it cannot call the getRange method of null. I'm not sure if I'm using OpenById correctly or if I can even use that in this situation.
OK I've got it working now. It copies the row perfectly and it copies only the cells I want. Now I need help with the pasting part. It copies everything fine and puts it into the other sheet great, but I need it to copy into the next available row and into the first available columns. So if row 5 is the last column of data, I need it to paste into row 6 and take up the first 6 or so columns.
This is what I have so far.
function menuItem1() {
var sss = SpreadsheetApp.openById('0AgcCWQn-aoI1dFpLVE4tSENwcThrYnlMUzhuRmdWU2c'); // sss = source spreadsheet Steve2
var ss = sss.getSheetByName('Sheet1'); // ss = source sheet
//Message box asking user to specify the row to be copied
var answer = Browser.inputBox('What row would you like to copy?');
var range = parseInt(answer);
var array = [1,2,3,9,12,30];
//Runs a loop to iterate through array, using array elements as column numbers
for(var i = 0; i < array.length; i++){
var SRange = ss.getRange(answer,1,1,array[i]);
//get A1 notation identifying the range
var A1Range = SRange.getA1Notation();
//get the data values in range
var SData = SRange.getValues();
}
var tss = SpreadsheetApp.openById('0AgcCWQn-aoI1dF96X2dBT2dVVFZ2SU1NRWdYTDJhT2c'); // tss = target spreadsheet Corbin1
var ts = tss.getSheetByName('Sheet1'); // ts = target sheet
//set the target range to the values of the source data
ts.getRange(A1Range).setValues(SData);
//Confirmation message that the row was copied
Browser.msgBox('You have successfully copied Row: ' + answer);
}
You are getting this error maybe because your spreadsheet does not have a sheet called Steve2 or Cobin1. Try using the method master.getSheets()[0], this way you will get the first sheet without using their name.
You can algo use this piece of code to check the sheets names:
for(var x in master.getSheets()) {
Logger.log(master.getSheets()[x].getSheetName());
}
best,
In Google Spreadsheet I would like to take only the values from a complete list on one spreadsheet and append it to the bottom of a list on another spreadsheet. My trouble is that using the the copyValuesToRange() function errors the following:
Target sheet and source range must be on the same spreadsheet.
Here's my current code:
function transferList() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var target = SpreadsheetApp.openById("0ABCD");
var target_sheet = target.getSheetByName("RFPData");
var sheet = source.getSheetByName("RFP List");
var sheet_last_row = sheet.getLastRow() + 1;
var source_range = sheet.getRange("A2:I"+sheet_last_row);
var sWidth=source_range.getWidth() + 1;
var sHeight=source_range.getHeight() + 1;
var last_row=target_sheet.getLastRow();
source_range.copyValuesToRange(target_sheet , 1, sWidth,
last_row + 1, last_row + sHeight );
}
Any idea how I can get this to work?
As you've found, copyValuesToRange() is a Range method that affects a Sheet Object that is in the same Spreadsheet Object as the Range. There isn't an atomic method that will copy a range of values to another Spreadsheet, but there are a number of ways you could do it.
Here's one way.
From the source sheet, get all the data in one operation, by selecting the complete range of data using getDataRange() and then grabbing all values into a javascript array with getValues().
To ignore the first row of headers, use the javascript array method splice().
Locate your destination, which is on the target sheet, starting after the last row of data that's currently there, using getLastRow().
Write the source data (without the headers) to the destination sheet starting at the next row, using setValues().
Script:
function transferList() {
var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("RFP List");
var sourceData = sourceSheet.getDataRange().getValues();
sourceData.splice(0,1); // Remove header
var targetSS = SpreadsheetApp.openById("0ABCD").getSheetByName("RFPData");
var targetRangeTop = targetSS.getLastRow(); // Get # rows currently in target
targetSS.getRange(targetRangeTop+1,1,sourceData.length,sourceData[0].length).setValues(sourceData);
}
For some historic dashboard I created by importing and appending data, I use an add-on called Sheetgo. Save me programing time and help me with traceability issues.
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.
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.
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