In Google Apps Script, Im using the script below to create a pdf and send as an email. The problem is that when it creates the new sheet and copies across, the formulas are copied. The emailed PDF than shows a REF error.
I need to copy the Value and Format.
Thanks
function exportPDF() {
var originalSpreadsheet = SpreadsheetApp.getActive();
var message = "Please see attached";
var projectname = originalSpreadsheet.getRange("a2:c2").getValues();
var period = originalSpreadsheet.getRange("B24:c24").getValues();
var subject = projectname + " - Daily Control Totals - " + period;
var contacts = originalSpreadsheet.getSheetByName("Contacts");
var numRows = contacts.getLastRow();
var emailTo = contacts.getRange(2, 2, numRows, 1).getValues();
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var projectname = SpreadsheetApp.getActiveSpreadsheet();
sheet = originalSpreadsheet.getActiveSheet();
sheet.copyTo(newSpreadsheet);
newSpreadsheet.getSheetByName('Sheet1').activate();
newSpreadsheet.deleteActiveSheet();
DriveApp.getFileById(newSpreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:'Daily Totals.pdf',content:pdf, mimeType:'application/pdf'};
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
DriveApp.getFileById(newSpreadsheet.getId()).setTrashed(true);}
Currently, if you have references to other sheets in the sheet you are copying, after copying you will get REF errors, which makes sense as the data is no longer where it should be.
To avoid that when we can use Range's
copyTo(Range, Object);
method. However, this method can only be used within a single spreadsheet, so we need to create a temporary sheet that will store our values then copy the sheet to a new spreadsheet to send in an email:Updated: So your code would look something like this: