I have a spreadsheet with multiple sheets and I have another sheet with column A containing mail ids
and column B containing sheet names.
Whenever a sheet comes I will check with relevant mail ids to where the sheets have to be attached
For eg for sheetname 10001515ADC I have to attach the sheet to mail id guru3291#gmail.com and mail it.
Similarly for 10003810ADC the mail id is kumaraguru#aai.aero
The Code I worked on
function email(){
var heet= SpreadsheetApp.openById('1mbFTGxhvSbbttfkaezJpfU1TXNtJUPBvujREPi3yVwo');
var mid = heet.getSheetByName('Sheet1');
var getNames = mid.getDataRange().getValues();
getNames.shift();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheetsObj = {};
for (var i = 1; i < sheets.length; i++) {
sheetsObj[sheets[i].getSheetName()] = sheets[i];
}
Logger.log(sheetsObj);
for (var i = 0; i < getNames.length; i++) {
var r = getNames[i];
if (r[1] in sheetsObj) {
var ssID = ss.getId();
Logger.log(ssID);
var c =r[1];
var p =ss.getSheetByName(c);
p.activate;
Logger.log(p);
var sheetgId = ss.getActiveSheet().getSheetId();
Logger.log(sheetgId);
var sheetName = ss.getName();
Logger.log(sheetName);
}
var token = ScriptApp.getOAuthToken();
var email = r[0];
var subject = "Important Info!";
var body = "Latest Recency Report \n\nRegards,\n VOTV-ATM-OPS";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" +
"&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: { 'Authorization': 'Bearer ' + token}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".pdf", content:contents,
mimeType:"application//pdf"}]});
}
}
Your script is sending the wrong sheet because your activate request is not going through
This is due to the fact that you are referring to the method activate without calling it
To call a method, you need to reference it including the () brackets
So, modify p.activate; to p.activate();
See also Fucniton invoacation in Javascript.
SIDE NOTE
You do not need to activate a sheet to work with it.
The lines
var p =ss.getSheetByName(c);
p.activate();
var sheetgId = ss.getActiveSheet().getSheetId();
can be replaced by
var p =ss.getSheetByName(c);
var sheetgId = p.getSheetId();
Related
I have previously been able to copy rows from one Spreadsheet to another, however what I am trying to do now is copy a row to a specific spreadsheet that is linked on the same row and I can't seem to work it out.
I have around 500 rows of names with data (I cannot share a sheet as my firms Google does not allow for sharing externally but I have a screenshot of dummy data below). I used a formula to find the Unique names and then created a Google Sheet for each person and linked the Sheet back to the master data.
Master Data Sheet (tab is called Sheet1)
I am looking for a script that will work through the sheet, copying the rows to the link that is on the same row but I just can't figure it out - the following script does not work but I am at a loss so any help would be appreciated.
Apologies if I haven't explained myself very well!!
function copyTo(){
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Sheet1");
var data = srcSheet.getDataRange().getValues();
for(var i = 1; i < data.length; i++) {
var row = data[i];
var link = row[3];
var id = row[4];
var complete = row[5];
var COMPLETE = "Complete"
if(link !== "" && complete !== "Complete"){
var srcRange = srcSheet.getRange("A" + i + ":C" + i);
var linkID = id.toString()
var tarSS = DriveApp.getFileById(linkID);
var tarSheet = tarSS.getSheetbyName("Sheet1");
var tarRow = tarSheet.getLastRow();
//tarSheet.insertRowAfter(tarRow);
var tarRange = tarSheet.getRange("A" + (tarRow+1) + ":C" + (tarRow+1));
srcRange.copyTo(tarRange);
srcSheet.getRange(i+1,6).setValue(COMPLETE)
}
}};
Try this:
function copyTo() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("Sheet1");
var vs = sh.getDataRange().getValues();
for (var i = 1; i < vs.length; i++) {
var row = vs[i];
var link = row[3];
var id = row[4];
var complete = row[5];
var COMPLETE = "Complete"
if (link !== "" && complete !== "Complete") {
var rg = sh.getRange("A" + i + ":C" + i);
var linkID = id.toString()
var tarSS = SpreadsheetApp.openById(linkID);
var tarSheet = tarSS.getSheetbyName("Sheet1");
var tarRow = tarSheet.getLastRow();
var tarRange = tarSheet.getRange("A" + (tarRow + 1) + ":C" + (tarRow + 1));
rg.copyTo(tarRange);
sh.getRange(i + 1, 6).setValue(COMPLETE)
}
}
};
As much as I understand you question here is the script which will work for you exactly you want .
This will copy data from sheet you want and then create a new spreadsheet and paste into that sheet then link will show of this in same sheet from data copied
Let me know how this worked .
Code.gs
const sendDataToSheet = () => {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const ws = ss.getSheetByName(''paste here your sheet name'')
const newSheet = SpreadsheetApp.create("give new sheet name here")
ws.copyTo(newSheet).setName("Copied Data")
const sheetURL = newSheet.getUrl()
ws.insertRowBefore(1)
ws.getRange(1,1).setValue(sheetURL)
}
I've noticed my sent email from Google App Script with Form-Submission Triggered and found that 3 in almost 300 of my emails are sent twice!
I have no idea about this and here is what i wrote.
function emailAsExcel(spreadsheetId,subject,message,fileName,link) {
var ss = SpreadsheetApp.openById(spreadsheetId);
var fileId = ss.getId();
var data = ss.getActiveSheet().getRange('A2:D2').getValues();
var url = 'https://docs.google.com/spreadsheets/d/'+fileId+'/export?format=xlsx';
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
})
var blobs = response.getBlob().setName(fileName+'.xlsx');
var picblobs = DriveApp.getFileById(getIdFromUrl(link)).getBlob().setName(fileName + '.jpg');
var sender = "xxx#gmail.com"+","+ "yyy#gmail.com";
var email = sender;
MailApp.sendEmail(email,subject,message,{attachments: [blobs, picblobs]});
}
function genFile(){
var ss = SpreadsheetApp.openById('xxxxxxxxxxxx');
var sheet = ss.getSheetByName('yyyyy');
var lastRow = sheet.getRange(1,9,sheet.getLastRow()).getValues().filter(String).length;
Logger.log(lastRow);
var date = sheet.getRange('A'+lastRow).getValue();
var name = sheet.getRange('J'+lastRow).getValue();
var surname = sheet.getRange('K'+lastRow).getValue();
var number = sheet.getRange('E'+lastRow).getValue();
var prov = sheet.getRange('F'+lastRow).getValue();
var brand = sheet.getRange('G'+lastRow).getValue();
var link = sheet.getRange('I'+lastRow).getValue();
var subject = name+'_'+surname;
var message =
'customer fullname : '+ name +' '+surname+'\n'
+'num : '+ number + prov+'\n'
+'bra : '+ brand +'\n'
var fileName = name+ ' ' +surname;
Logger.log(link);
var destination = DriveApp.getFileById('aaaaaaaaaaaaaaaa').makeCopy().getId();
var newFile = SpreadsheetApp.openById(destination);
var newSheet = newFile.getSheetByName('bbbbbbbbb');
newSheet.getRange('A2').setValue(date);
newSheet.getRange('B2').setValue(name+' '+surname);
newSheet.getRange('C2').setValue(number);
newSheet.getRange('D2').setValue(prov);
newSheet.getRange('E2').setValue(brand);
newFile.setName(fileName);
emailAsExcel(destination,subject,message,fileName,link);
}
function getIdFromUrl(url) { return url.match(/[-\w]{25,}/); }
genFile();
}
I try to figure it out but I still do not know what happened, so I need you guys' advice.
Thank you in advance!
This likely happens when you (or another Google account that has access to this script) has created multiple triggers.
Go to https://script.google.com/home/triggers, choose your project and remove any duplicate onSubmit triggers.
my google sheet will email a PDF copy of the sheet to a list of 4 emails ( in cells L5:L8 )
but it seems that the email in cell L8 never picked , logger shows it in the array ! .
see my code and help figuring the problem !? I'm suspecting something wrong in my FOREACH loop .
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L11').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheet = ss.getActiveSheet();
var sheetName = ss.getName();
var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var token = ScriptApp.getOAuthToken();
var setcolor= SpreadsheetApp.getActiveSheet().setTabColor("#0000A0");
var emails= sheet.getRange("L5:L8").getValues();
var subject = "Daily report ";
var body = "Please find the attached" +" "+ key ;
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var tempSheet = ss.insertSheet("tempSheet"); // Added
sheet.getRange("A1:J27").copyTo(tempSheet.getRange(1, 1)); // Added
SpreadsheetApp.flush(); // Added
var sheetgId = tempSheet.getSheetId(); // Added
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {headers: {'Authorization': 'Bearer ' + token}});
var contents = result.getContent();
emails.forEach(function(email){
MailApp.sendEmail(email.toString(),sheetName ,body, {attachments: [{fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf"}]});
ss.deleteSheet(tempSheet); // Added
})
}
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for ( var i = 0 ; i<sheets.length ; i++) {
var sheet1 = sheets[i];
sheet1.getRangeList(['L3','L11']).clearContent();
}
}
this script sends a pdf copy to my email when I type Send in cell L6 , this code send the whole sheet and I need to send as only A1:J22 , any Ideas ?
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
You want to retrieve the cells of A1:J22 and want to create them to PDF data.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In this modification, create a temporal sheet and copy the values of the cells of A1:J22 to it. Then, the temporal sheet is converted to PDF file. And, the temporal sheet is deleted.
Modified script:
When your script is modified, please modify as follows.
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheet = ss.getActiveSheet(); // Added
// var sheetgId = ss.getActiveSheet().getSheetId(); // removed
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var tempSheet = ss.insertSheet("tempSheet"); // Added
sheet.getRange("A1:J22").copyTo(tempSheet.getRange(1, 1)); // Added
SpreadsheetApp.flush(); // Added
var sheetgId = tempSheet.getSheetId(); // Added
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {headers: {'Authorization': 'Bearer ' + token}});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments: [{fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf"}]});
ss.deleteSheet(tempSheet); // Added
}
}
References:
insertSheet(sheetName)
copyTo(destination)
deleteSheet(sheet)
If I misunderstood your question and this was not the direction you want, I apologize.
In the new Google Spreadsheet I have a large script that clears the contents from many cells throughout 8 different sheets.
The formulas that total up the sheet is the only section that is protected, but I keep getting the error on the .clearContent(); method when the script isn't touching any of the protected cells.
Any thoughts? This is the identical script used (working perfect) on the old spreadsheets.
function masterCloseWeek() {
var hideLiqOrder = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('LIQUOR ORDER');
hideLiqOrder.hideSheet();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var costReport = spreadsheet.getSheetByName('COST REPORT').activate();//Moves sheet to position 1
spreadsheet.moveActiveSheet(1);
var invoiceLog = spreadsheet.getSheetByName('INVOICE LOG').activate();//Moves sheet to position 2
spreadsheet.moveActiveSheet(2);
var dailyInventory = spreadsheet.getSheetByName('DAILY INVENTORY').activate();//Moves sheet to position 3
spreadsheet.moveActiveSheet(3);
SpreadsheetApp.flush();
var spreadsheetId = 'xxxxxxxxxxxx'; //ID
var file = Drive.Files.get(spreadsheetId);
var url = file.exportLinks['application/pdf'];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
//var pdf = response.getBlob();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getName();
var pdf = response.getBlob().setName(ss.getName() + '.pdf');
var CopyDate = Utilities.formatDate(new Date(), "GMT-3", "MM/dd/yyyy HH:mm"); // Funtion Date + Format
DocsList.createFile(pdf);
MailApp.sendEmail({
to:"myEmail#test.com",
subject: "Blank (v2.0) Weekly File Attached" + "_" + "Sent on " + CopyDate,
body:"(This is an automated email.).....Attached is a copy of the weekly file sent on" + " "+CopyDate,
attachments: [pdf]
})
var hideLiqOrder = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('LIQUOR ORDER');
hideLiqOrder.showSheet();
var liquorInventory = SpreadsheetApp.getActive().getSheetByName('LIQUOR INVENTORY');
liquorInventory.getRange('J6:J588').copyTo(liquorInventory.getRange('M6:M588'),{contentsOnly:true});
var foodInventory = SpreadsheetApp.getActive().getSheetByName('FOOD INVENTORY');
foodInventory.getRange('G5:G622').copyTo(foodInventory.getRange('I5:I622'),{contentsOnly:true});
//Finished closing week
//Starting a new week
var activeSheet = SpreadsheetApp.getActiveSpreadsheet();
var costReport = activeSheet.getSheetByName('COST REPORT');
var FraminghamSnapShot = activeSheet.getSheetByName('FraminghamSnapShot');
costReport.getRange('E12:E16').copyTo(FraminghamSnapShot.getRange('B23:B27'),{contentsOnly:true});
This is the first error, when it tries to clear invoiceLog.getRange('A3:L52').clearContent();
var invoiceLog = SpreadsheetApp.getActive().getSheetByName('INVOICE LOG');
invoiceLog.getRange('A3:L52').clearContent();
var dailyInventory = SpreadsheetApp.getActive().getSheetByName('DAILY INVENTORY');
dailyInventory.getRange('C5:C9').clearContent();
dailyInventory.getRange('D6:I9').clearContent();
dailyInventory.getRange('C13:C17').clearContent();
dailyInventory.getRange('D14:I17').clearContent();
dailyInventory.getRange('C21:C25').clearContent();
dailyInventory.getRange('D22:I25').clearContent();
dailyInventory.getRange('C29:C33').clearContent();
dailyInventory.getRange('D30:I33').clearContent();
dailyInventory.getRange('C37:C41').clearContent();
dailyInventory.getRange('D38:I41').clearContent();
dailyInventory.getRange('C45:C49').clearContent();
dailyInventory.getRange('D46:I49').clearContent();
dailyInventory.getRange('C55:C59').clearContent();
dailyInventory.getRange('D56:I59').clearContent();
dailyInventory.getRange('C63:C67').clearContent();
dailyInventory.getRange('D64:I67').clearContent();
dailyInventory.getRange('C71:C75').clearContent();
dailyInventory.getRange('D72:I75').clearContent();
dailyInventory.getRange('C79:C83').clearContent();
dailyInventory.getRange('D80:I83').clearContent();
dailyInventory.getRange('C87:C91').clearContent();
dailyInventory.getRange('D88:I91').clearContent();
dailyInventory.getRange('C95:C99').clearContent();
dailyInventory.getRange('D96:I99').clearContent();
dailyInventory.getRange('C105:C109').clearContent();
dailyInventory.getRange('D106:I109').clearContent();
dailyInventory.getRange('C113:C117').clearContent();
dailyInventory.getRange('D114:I117').clearContent();
dailyInventory.getRange('C121:C125').clearContent();
dailyInventory.getRange('D122:I125').clearContent();
dailyInventory.getRange('C129:C133').clearContent();
dailyInventory.getRange('D130:I133').clearContent();
dailyInventory.getRange('C137:C141').clearContent();
dailyInventory.getRange('D138:I141').clearContent();
dailyInventory.getRange('C145:C149').clearContent();
dailyInventory.getRange('D146:I149').clearContent();
var foodInventory = SpreadsheetApp.getActive().getSheetByName('FOOD INVENTORY');
foodInventory.getRange('D5:F622').clearContent();
var liquorInventory = SpreadsheetApp.getActive().getSheetByName('LIQUOR INVENTORY');
liquorInventory.getRange('E6:I371').clearContent(); //Vodka thru Wines
liquorInventory.getRange('G375:I433').clearContent(); //Draft Beer
liquorInventory.getRange('G437:I535').clearContent(); //Bottle Beer
liquorInventory.getRange('E539:I588').clearContent(); //Non Alcoholic
var dailySalesSheet = SpreadsheetApp.getActive().getSheetByName('DAILY SALES SHEET');
dailySalesSheet.getRange('B4:H11').clearContent(); //Sales Categories
var costReport = SpreadsheetApp.getActive().getSheetByName('COST REPORT');
costReport.getRange('F12:F16').clearContent(); //Theoreticals
costReport.getRange('D20:D20').clearContent(); //Week Ending Date
var safeAudit = SpreadsheetApp.getActive().getSheetByName('SAFE AUDIT');
safeAudit.getRange('C3:P11').clearContent();
safeAudit.getRange('C14:P18').clearContent();
safeAudit.getRange('C22:P22').clearContent();
var destination = SpreadsheetApp.getActiveSpreadsheet();
Browser.msgBox('Closed Successfully','Your week has been successfully closed\\n and emailed.', Browser.Buttons.OK);
var name = Browser.inputBox('Enter Week Ending Date ONLY', 'Example: 11-5-14 \\n\\n', Browser.Buttons.OK);
destination.rename("BlankWE" + name);
costReport.getRange('D20').setValue(name);
}
Is there a better more efficient way to clear cells? Would that help solve the issue?
Sean.
Well, I don't find anything wrong in your invoiceLog.getRange('A3:L52').clearContent();, it works perfectly for me.