In Google Sheets I have a script I'm using to create a new sheet for each Google Form that is submitted. It is supposed to create a new sheet with name based on the last column, column G(which isn't a form submitted column). Then it takes the information from the last row and the heading row and copy it to the first two rows of the created sheet. It also adds formulae to cells to put the info into columns(transpose) and format it based on a created sheet.
Right now it is creating the sheet and copying the formulae and format, but not giving it the proper name or pulling the last row information.
Please help!
~Charles
I have copied the code below:
function onFormSubmit() {
// onFormSubmit
// get submitted data
var ss = SpreadsheetApp.openById(
'...');
var sheet = ss.getSheetByName("Responses");
var headings = sheet.getRange(1,1,1,
sheet.getLastColumn()).getValues();
var lastRow = sheet.getRange(sheet.getLastRow(),1,1,
sheet.getLastColumn()).getValues();
var studentUsername = lastRow[0][6];
// check if username has sheet
if(ss.getSheetByName(studentUsername)){
var userSheet = ss.getSheetByName(studentUsername);
// if not make
} else {
var userSheet = ss.insertSheet(studentUsername);
userSheet.getRange(1,1,1,
headings[0].length).setValues(headings);
}
// copy submitted data to user's sheet
userSheet.appendRow([lastRow]);
userSheet.appendRow(['=CONCATENATE(B6," ",B5)']);
userSheet.appendRow(['=TRANSPOSE(B1:2)']);
userSheet.hideRows(1,2);
userSheet.setColumnWidth(1, 500);
userSheet.setColumnWidth(2, 500);
var FormatSheet = ss.getSheetByName("Format");
var FormatRange = FormatSheet.getRange("a3:b28");
FormatRange.copyFormatToRange(userSheet,1,3,3,28);
}
With some help from the comments and playing around, i figured out the code I need. Big thanks to #Cooper!
Here it is:
function onFormSubmit() {
// onFormSubmit
// get submitted data
var ss = SpreadsheetApp.openById(
'Sheet_ID');
var sheet = ss.getSheetByName("Responses");
var row = sheet.getLastRow();
var Col = sheet.getLastColumn();
var headings = sheet.getRange(1,1,1,
Col).getValues();
var lastRow = sheet.getRange(row, 1, 1, Col);
var studentUsername = sheet.getRange(row, Col).getValue();
// check if username has sheet
if(ss.getSheetByName(studentUsername)){
var userSheet = ss.getSheetByName(studentUsername);
// if not make
} else {
var userSheet = ss.insertSheet(studentUsername);
userSheet.getRange(1,1,1,
headings[0].length).setValues(headings);
}
// copy submitted data to user's sheet
userSheet.appendRow(lastRow.getValues()[0]);
userSheet.appendRow(['=CONCATENATE(B6," ",B5)']);
userSheet.appendRow(['=TRANSPOSE(B1:2)']);
userSheet.hideRows(1,2);
userSheet.setColumnWidth(1, 500);
userSheet.setColumnWidth(2, 500);
var FormatSheet = ss.getSheetByName("Format");
var FormatRange = FormatSheet.getRange("a3:b28");
FormatRange.copyFormatToRange(userSheet,1,3,3,28);
}
Related
Is it possible to create a function that will clear a cell when a URL on the active row is clicked? I need to clear the cell on the active row in column AG, or [32], whenever the response link on that cell is activated to be opened to go back to the form.
I have the code that creates the date value in the column I need cleared. The code is to disburse emails automatically (on a trigger) when an email is submitted. However, when a response needs to be added to the form, the 'Response Link' needs to be activated so the user can be taken back to the form to fill in response data. I want the emails to go out again when the form is updated. But because I added a date there to stop emails from going out over and over, updated emails cannot send. Once the form is resubmitted, it will put a date back into the cell.
function disburseEmails(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Form Responses 1');
var allRange = sheet.getDataRange();
var allData = allRange.getValues();
allData.shift();
allData.forEach(function(row,i) {
if(row[32] === '') {
// get data
var dateSubmitted = row[0];
var dateEdited = row[1];
var studentID = row[2];
var studentName = row[3];
var responseLink= row[4];
var submitRespond = row[5];
var senderName = row[6];
var senderEmail = row[7];
var senderPhone = row[8];
var senderExt = row[9];
var senderRole = row[10];
var senderReason = row[11];
var senderAdditional = row[12];
var householdName = row[13];
var householdAddress = row[14];
var householdPhone = row[15]
var studentGrade = row[16];
var studentSchool = row[17];
var anySiblings = row[18];
var sibling1Name = row[19];
var sibling1Grade = row[20];
var sibling1School = row[21];
var sibling2Name = row[22];
var sibling2Grade = row[23];
var sibling2School = row[24];
var additionalSiblings= row[25];
var numberHomeVisit = row[26];
var responseContactName = row[27];
var responseContactRelationship = row[28];
var responseOutcome= row[29];
var responseAdditional = row[30];
var email = row[31];
var confirmSenderEmail = row[32];
// send an email to the sender for each row
sendEmail(dateSubmitted, email, dateEdited, studentID, studentName, responseLink, submitRespond, senderName, senderEmail, senderPhone, senderExt, senderRole, senderReason, senderAdditional, householdName, householdAddress, householdPhone, studentGrade, studentSchool, anySiblings, sibling1Name, sibling1Grade, sibling1School, sibling2Name, sibling2Grade, sibling2School, additionalSiblings, numberHomeVisit, responseContactName, responseContactRelationship, responseOutcome, responseAdditional);
// add date to confirm the sender email went out
var d = new Date();
sheet.getRange(i + 2, 33).setValue(d);
}
});
}
Let's asssume you have the links the needed in the F column:
function onSelectionChange(e) {
var range = e.range;
var sheet = e.range.getSheet();
if(range.getColumn() == 6) {
sheet.getRange("RANGE_OF_THE_CLEARED_CELL").clear();
}
}
The above snippet uses an onSelectionChange(e) trigger which will trigger whenever a cell is selected. In order to check that a cell from the F row is selected, a condition is set and based on that, the cell wanted is cleared.
The code makes use the e event object which contains information about which cell has been selected.
Note
This works for all the cells in the F column, so if you want to make it specific to a particular cell, you can just add another condition and/or a loop to reflect the data you want accordingly.
Reference
Apps Script Triggers;
Apps Script Event Objects ;
Apps Script Class Sheet - getRange
I have created a simple emailing script for a google sheet. I need it to attach the PDF of the active file, but only 3 sheets (the 3 unhidden sheets). I have tried several things but nothing seems to work, I am honestly not an expert in Google script so I may be missing something obvious. Following is my code:
function sendEmails() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Email');
var startRow = 2; // First row of data to process
var numRows = 1; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var subject = row[2];
var file= SpreadsheetApp.getActive();
MailApp.sendEmail(emailAddress, subject, message,{cc:"example#gmail.com",attachments:[file.getAs(MimeType.PDF)]});
}
}
What it does is attach the whole spreadsheet as a PDF, which doesn't help me because there are a lot of hidden sheets that I don't need in the PDF. Please help me!! Thanks!
The function will send emails to recipient in the Emails Sheet which also contains the subject and the message. It also creates a PDF of the current Spreadsheet with the sheets that are in the incl array. After the email is sent it returns the sheets back to their original visibility state.
function emailAsPDF() {
var ss=SpreadsheetApp.getActive();
var incl=['Sheet2','Emails'];
var pdfFolderId="Folder Id";
var folder=DriveApp.getFolderById(pdfFolderId);
var sObj={shA:[]};
var shts=ss.getSheets();
shts.forEach(function(sh,i){
sObj.shA.push(sh.getName());
if(sh.isSheetHidden()) {
sObj[sh.getName()]='hide';
}else{
sObj[sh.getName()]='show';
}
if(incl.indexOf(sh.getName())!=-1) {
sh.showSheet();
}else{
sh.hideSheet();
}
});
var file=folder.createFile(ss.getBlob()).setName(ss.getName()).getAs(MimeType.PDF);
var sh=ss.getSheetByName('Emails');
var rg=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn());
var hA=sh.getRange(1,1,1,sh.getLastColumn()).getValues()[0];
var hObj={};
hA.forEach(function(e,i){if(e){hObj[e]=i;}})
var vA=rg.getValues();
vA.forEach(function(r,i){
var recipient=r[hObj.recipient];
var subject=r[hObj.subject];
var message=r[hObj.message];
GmailApp.sendEmail(recipient, subject, message, {attachments:[file]})
})
sObj.shA.forEach(function(name,i){
if(sObj[name]=='hide') {
ss.getSheetByName(name).hideSheet();
}else{
ss.getSheetByName(name).showSheet();
}
});
}
This is an image of my Emails sheet:
I know...It's pretty trivial but you can improve it as you wish.
I have been working on a google sheet that that receives a form submission.
Once the submission comes in I need a script to move the rows of data to different tabs depending on the name shown in column C.
I have extensively searched for solutions on stack overflow and I am very close to a solution right now through the code I have found and edited.
I have a script that will move historic dates to a different tab and leave all future dates in the original tab based in the logic of the date being older than today.
All I need to do now is modify this to move the rows with the name "John" in column C to the John tab and ignore the date.
Once I can get one name to work I am confident I can make this work for multiple names and multiple tabs.
Please feel free to create a copy of the following test sheet I have been working on.
link:
https://docs.google.com/spreadsheets/d/1zJpylrD_5hzScW3lIjIQQSKiY0Aan6Wkm_h_IbVrVXM/edit#gid=0
function MovePastDates() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var entrySheet = ss.getSheetByName("Entry Sheet");
var franksSheet = ss.getSheetByName("Franks Sheet");
var lastColumn = entrySheet.getLastColumn();
for(var i = entrySheet.getLastRow(); i > 0; i--){
var dateCell = entrySheet.getRange(i, 1).getValue();
var today = new Date();
var test = new Date(dateCell);
// If the value is a valid date and is a past date, we remove it from the sheet to paste on the other sheet
if(test < today){
var rangeToMove = entrySheet.getRange(i, 1, 1, entrySheet.getLastColumn()).getValues();
franksSheet.getRange(franksSheet.getLastRow() + 1, 1, 1, entrySheet.getLastColumn()).setValues(rangeToMove);
entrySheet.deleteRow(i);
}
}
}
The final result should be a google sheet that receives form entries.
Each entry will be allocated to a specific person who will only have edit permissions to there own tab only where they can approve/decline requests submitted through the form.
All other users of the sheet will have view only access.
I wanted two scripts:
1) Script to move form submission rows to a specific tab dependent on person’s name
(I was going to set up a trigger every minute for this)
2) Script to move past dates into an historic sheet
(I was going to set up a trigger every night for this)
I have been able to modify your code to achieve the desired function, it may not be the most efficient but it appears to work well.
Script One is:
function moveRowsToNamesSheets() { //Name of function
var sObj={John:'Johns Sheet',Frank:'Franks Sheet',David:'Davids Sheet'}; // Put key work and sheet name here in format eg.( keyWord1: 'sheet name to move keyWord1 to')
var ss=SpreadsheetApp.getActive(); // ??
var esh=ss.getSheetByName('Entry Sheet'); //Sheet data is being pulled form
var fsh=ss.getSheetByName('Franks Sheet'); //unsure why one of the sheets is named here
var erg=esh.getDataRange(); // Not sure of function now that I am not using dates
var evA=erg.getValues(); // ??
var d=0; //??
//var today=new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()).valueOf(); // Didnt need this line
for(var i=1;i<evA.length;i++) { //??
if(/*new Date(evA[i][0]).valueOf() < today*/ evA[i][2]=='John' ||evA[i][2]=='Frank' ||evA[i][2]=='David') { //Keywords used go here, what does the [2] mean?
ss.getSheetByName(sObj[evA[i][2]]).appendRow(evA[i]); //??
esh.deleteRow(i+1-d);
d++; //increments d by one
}
}
}
Script Two is:
function HistoricDates() {
// Initialising
var ss = SpreadsheetApp.getActiveSpreadsheet();
//--------------- Franks Sheets --------------------
var franksSheet = ss.getSheetByName("Franks Sheet");
var PastSheet = ss.getSheetByName("Historic Requests");
var lastColumn = franksSheet.getLastColumn();
// Check all values from your "Franks Sheet" sheet
for(var i = franksSheet.getLastRow(); i > 0; i--){
// Check if the value is a valid date
var dateCell = franksSheet.getRange(i, 4).getValue(); //Dates in column 4
if(isValidDate(dateCell)){
var today = new Date();
var test = new Date(dateCell);
// If the value is a valid date and is a past date, we remove it from the sheet to paste on the other sheet
if(test < today){
var rangeToMove = franksSheet.getRange(i, 1, 1, franksSheet.getLastColumn()).getValues();
PastSheet.getRange(PastSheet.getLastRow() + 1, 1, 1, franksSheet.getLastColumn()).setValues(rangeToMove);
franksSheet.deleteRow(i);
}
}
}
//---------------------- Johns Sheets -------------------------
var johnsSheet = ss.getSheetByName("Johns Sheet");
var pastSheet = ss.getSheetByName("Historic Requests");
var lastColumn = johnsSheet.getLastColumn();
// Check all values from your "Johns Sheet" sheet
for(var i = johnsSheet.getLastRow(); i > 0; i--){
// Check if the value is a valid date
var dateCell = johnsSheet.getRange(i, 4).getValue(); //Dates in column 4
if(isValidDate(dateCell)){
var today = new Date();
var test = new Date(dateCell);
// If the value is a valid date and is a past date, we remove it from the sheet to paste on the other sheet
if(test < today){
var rangeToMove = johnsSheet.getRange(i, 1, 1, johnsSheet.getLastColumn()).getValues();
pastSheet.getRange(pastSheet.getLastRow() + 1, 1, 1, johnsSheet.getLastColumn()).setValues(rangeToMove);
johnsSheet.deleteRow(i);
}
}
}
//--------------- Davids Sheets --------------------
var davidsSheet = ss.getSheetByName("Davids Sheet");
var pastSheet = ss.getSheetByName("Historic Requests");
var lastColumn = davidsSheet.getLastColumn();
// Check all values from your "Davids Sheet" sheet
for(var i = davidsSheet.getLastRow(); i > 0; i--){
// Check if the value is a valid date
var dateCell = davidsSheet.getRange(i, 4).getValue();//Dates in column 4
if(isValidDate(dateCell)){
var today = new Date();
var test = new Date(dateCell);
// If the value is a valid date and is a past date, we remove it from the sheet to paste on the other sheet
if(test < today){
var rangeToMove = davidsSheet.getRange(i, 1, 1, davidsSheet.getLastColumn()).getValues();
pastSheet.getRange(pastSheet.getLastRow() + 1, 1, 1, davidsSheet.getLastColumn()).setValues(rangeToMove);
davidsSheet.deleteRow(i);
}
}
}
}
// Check is a valid date
function isValidDate(value) {
var dateWrapper = new Date(value);
return !isNaN(dateWrapper.getDate());
}
The working spreadsheet is located here:
https://docs.google.com/spreadsheets/d/1VCONRkBpkva-KrFDO2bFV8ZTp1U168QWAGavcKCa_uQ/edit?usp=sharing
I think this is what you want:
function movePastDatesOrJohn() {
var sObj={John:'Johns Sheet',Frank:'Franks Sheet',David:'Davids Sheet'};
var ss=SpreadsheetApp.getActive();
var esh=ss.getSheetByName('Entry Sheet');
var fsh=ss.getSheetByName('Franks Sheet');
var erg=esh.getDataRange();
var evA=erg.getValues();
var d=0;
var today=new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()).valueOf();
for(var i=1;i<evA.length;i++) {
if(new Date(evA[i][0]).valueOf() < today || evA[i][2]=='John') {
ss.getSheetByName(sObj[evA[i][2]]).appendRow(evA[i]);
esh.deleteRow(i+1-d);
d++;
}
}
}
So Franks Sheet and Davids Sheet only get the rows that are older than today. But Johns Sheet gets all of the row that are Johns and disregards the date. I think that's what you wanted.
By the way, did you know that if you more that one form attached to your spreadsheet you can tell which response sheet the formSubmit trigger is writing too, with the event object range? Using sheet name = e.range.getSheet().getName();
and thanks for the help. I've got a noob question, and need a noob answer.
Trying to email a specific google sheet as a pdf weekly, but script emails out whatever sheet happens to be open at the time.
Stole various snippets of code, here's what I've got: (And no, I don't think that this block of code was formatted and posted correctly.)
function endOfWK_1 () {
//This script converts all formulas to values in the currently displayed sheet, then converts the currently displayed sheet to a pdf, then emails the
pdf as an attachment to the addresses shown in cell B17 in the "Email" sheet.
//Replace all formulas in range "WK 1!A6:A29" with values
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('WK 1');
var range = sheet.getRange("WK 1!A6:A29");
range.copyTo(range, {contentsOnly: true});
// FOR WK1 ONLY!!!
// Set the Active Spreadsheet so we don't forget
var originalSpreadsheet = SpreadsheetApp.getActive();
// Set the message to attach to the email.
var message = "Please see attached.";
// Get Dates from Email!B5
var period = originalSpreadsheet.getRange("Email!B5").getValues();
// Construct the Subject Line
var subject = period;
// Get contact details from "Email" sheet and construct To: Header
var contacts = originalSpreadsheet.getSheetByName("Email");
var numRows = contacts.getLastRow();
var emailTo = contacts.getRange(17, 2, numRows, 1).getValues();
// Create a new Spreadsheet and copy the current sheet into it.
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var projectname = SpreadsheetApp.getActiveSpreadsheet();
sheet = originalSpreadsheet.getActiveSheet();
sheet.copyTo(newSpreadsheet);
// Find and delete the default "Sheet1"
newSpreadsheet.getSheetByName('Sheet1').activate();
newSpreadsheet.deleteActiveSheet();
// Create the PDF, currently called "Tracking Sheet.pdf"
var pdf = DriveApp.getFileById(newSpreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:'Tracking Sheet.pdf',content:pdf, mimeType:'application/pdf'};
// Send the freshly constructed email
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
// Delete the sheet that was created
DriveApp.getFileById(newSpreadsheet.getId()).setTrashed(true);
// Write the date and time that the script ran
var date = sheet.getRange('Statistics!A1').getValues();
SpreadsheetApp.getActiveSheet().getRange('Analysis!E5').setValues(date);
}
This is a bound script, attached to a google workbook containing 5 sheets. My problem is that my script always emails the sheet that happens to be open at the time.
I want to email one specific sheet, whether the workbook is open or closed. How can I do this? (I hope to install a trigger to make this script run automatically.)
Also, anyone want to critique my code?
Thanks to all.
I've fixed it up a little and added some comments. There were a lot of little things I fixed up biggest thing was that you should reuse variables that you've created.
This hasn't been tested...
function endOfWK_1 () {
//Replace all formulas in range "WK 1!A6:A29" with values
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetWK1 = activeSpreadsheet.getSheetByName('WK 1');
var range = sheetWK1.getRange("WK 1!A6:A29");
range.copyTo(range, {contentsOnly: true});
// FOR WK1 ONLY!!!
// Set the Active Spreadsheet so we don't forget
var originalSpreadsheet = SpreadsheetApp.getActive(); //this should probably be changed depending on what sheet you are trying to access: activeSpreadsheet.getSheetByName('Email')
// Set the message to attach to the email.
var message = "Please see attached.";
// Get Dates from Email!B5
var period = originalSpreadsheet.getRange("Email!B5").getValues();
// Construct the Subject Line
var subject = period;
// Get contact details from "Email" sheet and construct To: Header
var contacts = originalSpreadsheet.getSheetByName("Email");
var numRows = contacts.getLastRow();
var emailTo = contacts.getRange(17, 2, numRows, 1).getValues();
// Create a new Spreadsheet and copy the current sheet into it.
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export"); //Create a spreadsheet to copy to
// var originalSheet = activeSpreadsheet.getSheetByName("WK1"); Already defined above as sheetWK1
//var projectname = SpreadsheetApp.getActiveSpreadsheet(); Seems like this is not used.
sheetWK1.copyTo(newSpreadsheet); //Take the original sheet and copy it to the newSpreadsheet
// Find and delete the default "Sheet1"
newSpreadsheet.deleteSheet(newSpreadsheet.getSheetByName("Sheet1")); //We can just call the deleteSheet method.
// Create the PDF, currently called "Tracking Sheet.pdf"
var pdf = newSpreadsheet.getAs('application/pdf').getBytes(); //No need to get the Spreadsheet object again, as we alreat have it!
var attach = {fileName: 'Tracking Sheet.pdf', content: pdf, mimeType: 'application/pdf'};
// Send the freshly constructed email
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
// Delete the sheet that was created
newSpreadsheet.setTrashed(true); //Again no need to find the object. We have it.
// Write the date and time that the script ran
var date = sheet.getRange('Statistics!A1').getValues();
activeSpreadsheet.getRange('Analysis!E5').setValues(date);
}
The main issue was var originalSpreadsheet = SpreadsheetApp.getActive(); you are getting the active sheet and using that to create you pdf.
EDIT: I've cleaned up the whole thing a little and ended up with this. It hasn't been tested.
function endOfWK_1 () {
//Replace all formulas in range "WK 1!A6:A29" with values
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetWK1 = activeSpreadsheet.getSheetByName('WK 1');
var emailSheet = activeSpreadsheet.getSheetByName("Email");
var range = sheetWK1.getRange("WK 1!A6:A29");
range.copyTo(range, {contentsOnly: true});
// FOR WK1 ONLY!!!
// Set the message to attach to the email.
var message = "Please see attached.";
// Get Dates from Email!B5
var period = emailSheet.getRange("Email!B5").getValues();
// Construct the Subject Line
var subject = period;
// Get contact details from "Email" sheet and construct To: Header
var numRows = emailSheet.getLastRow();
var emailTo = emailSheet.getRange(17, 2, numRows, 1).getValues();
// Create a new Spreadsheet and copy the current sheet into it.
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
sheetWK1.copyTo(newSpreadsheet);
// Find and delete the default "Sheet1"
newSpreadsheet.deleteSheet(newSpreadsheet.getSheetByName("Sheet1"));
// Create the PDF, currently called "Tracking Sheet.pdf"
var pdf = newSpreadsheet.getAs('application/pdf').getBytes();
var attach = {fileName: 'Tracking Sheet.pdf', content: pdf, mimeType: 'application/pdf'};
// Send the freshly constructed email
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
// Delete the sheet that was created
DriveApp.getFileById(newSpreadsheet.getId()).setTrashed(true);
// Write the date and time that the script ran
var date = activeSpreadsheet.getRange('Statistics!A1').getValues();
activeSpreadsheet.getRange('Analysis!E5').setValues(date);
}
I am new to this and I am having some trouble trying to figure this out. I have a spreadsheet that collects data from a google form. I am trying to find a way to move that data based on a column answer to a different google sheet. (Not a sheet in the same document but a different document all together). It seems like there is some information about moving to a different tab in the same document, but not a different document.
I will first say that I tried just an IMPORTRANGE function, but that only mirrors the data, and does not let you update or change cells.
Here is what I have been able to piece together so far, but I may be way off.
I have a trigger that would run every hour.
function myFunction() {
var ss = SpreadsheetApp.openById('1U0I9SkbGkHgm-vRkwf2Ppc_yxlqrVlg2t8yKRy3sYuI');
var sheetOrg = ss.getSheetByName("Form Responses 1");
var value1ToWatch = "ANDERSON";
var value2ToWatch = "BARNES";
var sheetNameToMoveTheRowTo = "Sheet1"; //sheet has same name for each target openByID(" *url key* ")
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ts1 =SpreadsheetApp.openById("1PxV1PQrMdu_2aSru4dpan8cUgHYdlYPUp5anyzjMAms");
sheet1in = ts1.getSheetByName("Sheet1");
var ts2 = SpreadsheetApp.openById("1BYyQZNiXc2QqsyqWs7uazjl5B6mfFYM1xj3u8gWyYOQ");
sheet1in = ts2.getSheetByName("Sheet1");
arr = [],
values = sheetOrg.getDataRange().getValues(),
i = values.length;
while (--i) {
if (value1ToWatch.indexOf(values[i][1]) > -1) {
arr.unshift(values[i])
sheetOrg.deleteRow(i + 1)
sheet1in.getRange(sheet1in.getLastRow()+1, 1, arr.length,
arr[0].length).setValues(arr);
};
if (value2ToWatch.indexOf(values[i][1]) > -1) {
arr.unshift(values[i])
sheetOrg.deleteRow(i + 1)
sheet2in.getRange(sheet2in.getLastRow()+1, 1, arr.length,
arr[0].length).setValues(arr);
};
}
}
The sheet google forms dumps the information into is "Form Responses 1".
Column B is the cells I want to get the values from. (There are a total of 9 different values that it can be like "ANDERSON", "BARNES", "SMITH", etc).
For sheetNameToMoveTheRowTo is "Sheet1" - that may be confusing and I may need to change that, but for example
ts1 =SpreadsheetApp.openById("1PxV1PQrMdu_2aSru4dpan8cUgHYdlYPUp5anyzjMAms") the sheet name that I want the information moved to is "Sheet1".
ts2 = SpreadsheetApp.openById("1BYyQZNiXc2QqsyqWs7uazjl5B6mfFYM1xj3u8gWyYOQ") the sheet name is also "Sheet1" but in a different document.
I think if I were able to get the "ANDERSON" one to work, then I can just add additional variables for each possible response, and just copy and paste additional "IF" statements, just changing the valueToWatch and targetSheet values. <= if that is not correct please let me know
I have tried to both debug, and run the script above but nothing happens. There are no errors reported on the debug, but it is not moving any information over.
Any idea what I am doing wrong?
// UPDATE I got this to work. I have updated the code listed with what worked for me.
I think that copyTo() method will not work like you mentioned, it operates on same SpreadSheet. I'm sending you example with looping on source sheet data and then setting the target sheet values with it.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var allrange = ss.getActiveRange();
var range = sheet.getRange("A1:A10");
var values = range.getValues();
var allvals = [];
for(var i = 0; i < values.length; i++) {
allvals.push( values[i] ) ;
}
var dataLength = allvals.length;
// alert data
var ui = SpreadsheetApp.getUi();
// ui.alert( JSON.stringify(allvals) )
// copy to new Google SpreadSheet
var newSheet = SpreadsheetApp.openById('1F79XkNPWm2cCWlB2JP3K4tAYRESKUgtHK4Pn2vbJEiI').getSheets()[0];
var tmp = "A1:A" + dataLength ;
var newRange = newSheet.getRange( tmp );
newRange.setValues( allvals );
}
Here's a simple example of moving data from one spreadsheet to another.
function movingDataToSS(){
var ss=SpreadsheetApp.getActive();
var dss=SpreadsheetApp.openById('ssId');
var sh=ss.getActiveSheet();
var rg=sh.getDataRange();
var vA=rg.getValues();
var dsh=dss.getSheetByName('Sheet1');
var drg=dsh.getRange(1,1,rg.getHeight(),rg.getWidth()).setValues(vA);
}
If you interested in placing some conditions on your output by only getting output from odd rows and even columns.
function movingDataOddRowsAndEvenCols(){
var ss=SpreadsheetApp.getActive();
var dss=SpreadsheetApp.openById('ssId');
var sh=ss.getActiveSheet();
var rg=sh.getDataRange();
var vA=rg.getValues();
var h=rg.getHeight();
var w=rg.getWidth();
var dsh=dss.getSheetByName('Sheet1');
for(var i=0;i<h;i++){
var out=[];
if(i%2==0){
for(var j=0;j<w;j++){
if(j%2==1){
out.push(vA[i][j]);
}
}
dsh.appendRow(out);
}
}
}