Google Apps Sheets if statement not executing - google-apps-script

I've been working on a Google Sheets Script for my work, and have hit a road block. The goal here is to identify a cell in the heading row with a specific title and return the column it resides in. (Ie: in the heading row find "Email" in column "C" and return the number "3").
So far I've been able to find that the if statement isn't running. I'm pretty new to this language so any help would be greatly appreciated.
function findEmail(){
var searchString = "Email";
var data = sheet.getDataRange().getValues();
var row = 1;
var columnValues = sheet.getRange(row, 3, sheet.getLastRow()).getValues(); //1st is header row
var EMCol = columnValues.findIndex(searchString); //Row Index - 2\
var i;
for(i = 0; i<data.length;i++){
var j;
SpreadsheetApp.getActiveSheet().getRange('E2').setValue('Hello');
if(data[0][i] == EMCol){
SpreadsheetApp.getActiveSheet().getRange('E3').setValue('World');
// Logger.log((i+1))
// j = i+1
// return i+1;
}
return j;
};
}
This is what the sheet looks like after it has ran. As you can see nothing inside the if statement ran so there is no "World at E3.

When I run your code I get a TypeError, GAS doesn't have a findIndex() method. If you just want to find the column index then this function should do the job.
I'm not sure what you are trying to achieve with the Hello and World lines.
function findEmail() {
var searchString = "Email";
var data = sheet.getDataRange().getValues();
var columnIndex;
for (var i = 0; i < data[0].length; i++) {
if (data[0][i] == searchString) {
columnIndex = i + 1;
break;
}
}
Logger.log(columnIndex);
return columnIndex;
}

Related

How can Google Sheets Form Update Records from Results Using Google App script?

I have a program that filters and updates data from an existing sheet.
The program works as follows:
1. Find and filter out the required value
2. Enter data in [Adjustment] column then update to database in Record sheet.
I tried to try but my program doesn't seem to work.
I tried to edit the program code but when run it will affect the other columns and the [adjustment] column value is entered wrong.
This is my link program
function Searchold(){
var ss = SpreadsheetApp.getActiveSpreadsheet ();
var shtRecords = ss. getSheetByName ("RECORD");
var shtForm = ss. getSheetByName ("TEST") ;
var records = shtRecords. getDataRange () . getValues ();
var sField = shtForm. getRange ("A3").getValue ();
var sValue = shtForm.getRange ("A6").getValue();
var sCol = records [0].lastIndexOf(sField);
var results = records.filter(function(e){return sValue == e[sCol] });
if(results.length==0){SpreadsheetApp.getUi().alert("not found values");}
else{
shtForm.getRange(9,1,results.length,results[0].length).setValues(results);
}
}
function Updatenew(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var shtRecords = ss.getSheetByName("RECORD");
var shtForm = ss.getSheetByName("TEST");
var LastRow = shtForm.getRange("A8").getNextDataCell(SpreadsheetApp.Direction.DOWN).getLastRow();
var newData = shtForm.getRange(9,1,LastRow -1,7).getValues();
for(var i =0; i<newData.length;i++){
var oldData= shtRecords.getDataRange().getValues();
for(var j= 0;j<oldData.length;j++){
if(newData[i][0] ==oldData[j][0]){
var newData2 = [newData[i]];
shtRecords.getRange(j + 1,1,1,newData2[0].length).setValues(newData2);
}
}
}
}
Can you help me with the update program? Sincerely thank you
Modification points:
When I saw your showing script of Updatenew, I think that each row of var oldData = shtRecords.getDataRange().getValues() is used in each loop of for (var i = 0; i < newData.length; i++) {}. By this, each row is overwritten by each row of newData. By this, all searched rows in "RECORD" sheet are the same value. I thought that this might be the reason for your issue.
var oldData = shtRecords.getDataRange().getValues(); can be used one call.
In order to avoid this issue by modifying your script, as one of several methods, how about the following modification?
From:
for (var i = 0; i < newData.length; i++) {
var oldData = shtRecords.getDataRange().getValues();
for (var j = 0; j < oldData.length; j++) {
if (newData[i][0] == oldData[j][0]) {
var newData2 = [newData[i]];
shtRecords.getRange(j + 1, 1, 1, newData2[0].length).setValues(newData2);
}
}
}
To:
var oldData = shtRecords.getDataRange().getValues();
for (var j = 0; j < oldData.length; j++) {
for (var i = 0; i < newData.length; i++) {
if (newData[0][0] == oldData[j][0]) {
var newData2 = newData.splice(0, 1);
shtRecords.getRange(j + 1, 1, 1, newData2[0].length).setValues(newData2);
break;
}
}
}
Note:
At the above modification, setValues is used in a loop. In this case, the process cost becomes high. If you want to reduce the process cost of the script, how about using Sheets API? When Sheets API is used, how about the following modification? Please enable Sheets API at Advanced Google services.
To
var temp = newData.slice();
var data = shtRecords.getDataRange().getValues().reduce((ar, r, i) => {
if (temp[0][0] == r[0]) {
var t = temp.splice(0, 1);
t[0][2] = Utilities.formatDate(t[0][2], Session.getScriptTimeZone(), "dd/MM/yyyy");
t[0][4] = Utilities.formatDate(t[0][4], Session.getScriptTimeZone(), "dd/MM/yyyy");
ar.push({ range: `'RECORD'!A${i + 1}`, values: t });
}
return ar;
}, []);
Sheets.Spreadsheets.Values.batchUpdate({ data, valueInputOption: "USER_ENTERED" }, ss.getId());

Reduce script execution time - Google script

I made a script that works properly (does what I want it to), however, it's painfully slow and at this pace, it will finish in about 20 days. I can't wait for 20 days and I'm not good enough at this to make it faster on my own.
Here's a brief description of the task:
Masterlist - it's a sheet with 23 columns and 29000+ rows.
Seed - it's an empty sheet that I'm to copy the Masterlist to.
Duplicates - it's an empty sheet where I will store any duplicate rows.
The process:
Get the first line from Masterlist. Check if line already in Seed. If line not in Seed, add line. If line already in Seed, add line to Duplicates. Either way, delete the original line from the Masterlist.
The definition of duplicate:
Each line has an emails column. Column can be either a single email address, or multiple email addresses separated by "; ". If an email is found within line in Masterlist and already exists within line in Seed, this whole line is considered a duplicate.
Example:
"aaa#gmail.com" is not a duplicate of "a#gmail.com; aa#gmail.com"
"bbb#gmail.com" is a duplicate of "b#gmail.com; bbb#gmail.com"
Furthermore, if the emails cell is empty in the Masterlist, this is not considered a duplicate.
Here comes my code - it works but is not fast enough.
function getSheet(name){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
return sheet;
}
function getRowByID(sheet, rowID) {
var range = sheet.getRange(rowID, 1, 1, 23);
var value = range.getValues();
return [range, value];
}
//main executes the entire thing
function main(){
var sourceSheet = getSheet('Masterlist');
var targetSheet = getSheet('Seed');
var remainingSheet = getSheet('Duplicates');
var counter = sourceSheet.getLastRow();
var start = new Date();
while(counter >= 2){
var sourceLine = getRowByID(sourceSheet, 2)[1];
var duplicates = checkEmailMatch(sourceLine, targetSheet);
if(duplicates == 0){
targetSheet.appendRow(sourceLine[0]);
sourceSheet.deleteRow(2);
}
else{
remainingSheet.appendRow(sourceLine[0]);
sourceSheet.deleteRow(2);
}
counter--;
}
}
//iterates through existing lines in the Seed sheet (locates the email cell and reads its contents)
function checkEmailMatch(row, seed){
var sourceEmail = row[0][7];
var counter = seed.getLastRow();
var result = [];
if(!counter){
return 0;
}
else{
var j = 0;
var i = 2;
for(i; i <= counter; i++){
var seedLine = getRowByID(seed, i)[1];
var seedEmail = seedLine[0][7];
if(!seedEmail){}
else if(compareEmails(seedEmail, sourceEmail) == true) {
result[j] = i;
j++;
}
}
return result;
}
}
//Compares each email in Masterlist ("; " separated) with each email in Source ("; " separated)
function compareEmails(emailSeedCell, emailSourceCell){
var seedEmails = emailSeedCell.split("; ");
var sourceEmails = emailSourceCell.split("; ");
for(var i = 0; i < seedEmails.length; i++){
for(var j = 0; j < sourceEmails.length; j++){
if(seedEmails[i] == sourceEmails[j]) return true;
}
}
return false;
}
Please help me - if you need any additional info, I'd be happy to provide! Please note that this is my third script ever, so any feedback is welcome!
Thanks to everyone who chipped in to help, I managed to come up with this code that reduced the execution time more than 10000 times! Thanks, everyone - here's the code:
function sheetToArray(name){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
var counter = sheet.getLastRow();
var columns = sheet.getLastColumn();
var array = sheet.getRange(2, 1, counter, columns).getValues();
return array;
}
function compareEmails(emailSeedCell, emailSourceCell){
var seedEmails = emailSeedCell.split("; ");
var sourceEmails = emailSourceCell.split("; ");
var result = false;
for(var i = 0; i < seedEmails.length; i++){
for(var j = 0; j < sourceEmails.length; j++){
if(seedEmails[i] == sourceEmails[j]) result = true;
}
}
return result;
}
function save2DArrayToSpreadsheet(name, array){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
sheet.getRange(2, 1, array.length, array[0].length).setValues(array);
}
function main(){
var masterArray = sheetToArray('Masterlist');
var seedArray = [];
var duplicateArray = [];
for(var i = 0; i < masterArray.length; i++){
Logger.log(i);
if(!seedArray.length){
seedArray.push(masterArray[i]);
}
else if(!masterArray[i][7]){
seedArray.push(masterArray[i]);
}
else{
var result = false;
for(var j = 0; j < seedArray.length; j++){
if(compareEmails(seedArray[j][7], masterArray[i][7]) == true){
result = true;
}
}
if(result == true){
duplicateArray.push(masterArray[i]);
}
else{
seedArray.push(masterArray[i]);
}
}
}
save2DArrayToSpreadsheet("Seed", seedArray);
save2DArrayToSpreadsheet("Duplicates", duplicateArray);
}

I need to split a Google Sheet into multiple tabs (sheets) based on column value

I have searched many possible answers but cannot seem to find one that works. I have a Google Sheet with about 1600 rows that I need to split into about 70 different tabs (with about 20-30 rows in each one) based on the value in the column titled “room”. I have been sorting and then cutting and pasting but for 70+ tabs this is very tedious.
I can use the Query function but I still need to create a new tab, paste the function and update the parameter for that particular tab.
This script seemed pretty close:
ss = SpreadsheetApp.getActiveSpreadsheet();
itemName = 0;
itemDescription = 1;
image = 2;
purchasedBy = 3;
cost = 4;
room = 5;
isSharing = 6;
masterSheetName = "Master";
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Update Purchases')
.addItem('Add All Rows To Sheets', 'addAllRowsToSheets')
.addItem('Add Current Row To Sheet', 'addRowToNewSheet')
.addToUi();
}
function addRowToNewSheet() {
var s = ss.getActiveSheet();
var cell = s.getActiveCell();
var rowId = cell.getRow();
var range = s.getRange(rowId, 1, 1, s.getLastColumn());
var values = range.getValues()[0];
var roomName = values[room];
appendDataToSheet(s, rowId, values, roomName);
}
function addAllRowsToSheets(){
var s = ss.getActiveSheet();
var dataValues = s.getRange(2, 1, s.getLastRow()-1, s.getLastColumn()).getValues();
for(var i = 0; i < dataValues.length; i++){
var values = dataValues[i];
var rowId = 2 + i;
var roomName = values[room];
try{
appendDataToSheet(s, rowId, values, roomName);
}catch(err){};
}
}
function appendDataToSheet(s, rowId, data, roomName){
if(s.getName() != masterSheetName){
throw new Error("Can only add rows from 'Master' sheet - make sure sheet name is 'Master'");
}
var sheetNames = [sheet.getName() for each(sheet in ss.getSheets())];
var roomSheet;
if(sheetNames.indexOf(roomName) > -1){
roomSheet = ss.getSheetByName(roomName);
var rowIdValues = roomSheet.getRange(2, 1, roomSheet.getLastRow()-1, 1).getValues();
for(var i = 0; i < rowIdValues.length; i++){
if(rowIdValues[i] == rowId){
throw new Error( data[itemName] + " from row " + rowId + " already exists in sheet " + roomName + ".");
return;
}
}
}else{
roomSheet = ss.insertSheet(roomName);
var numCols = s.getLastColumn();
roomSheet.getRange(1, 1).setValue("Row Id");
s.getRange(1, 1, 1, numCols).copyValuesToRange(roomSheet, 2, numCols+1, 1, 1);
}
var rowIdArray = [rowId];
var updatedArray = rowIdArray.concat(data);
roomSheet.appendRow(updatedArray);
}
But I always get an unexpected token error on line 51 or 52:
var sheetNames = [sheet.getName() for each(sheet in ss.getSheets())];
(And obviously the column names, etc. are not necessarily correct for my data, I tried changing them to match what I needed. Not sure if that was part of the issue.)
Here is a sample of my data: https://docs.google.com/spreadsheets/d/1kpD88_wEA5YFh5DMMkubsTnFHeNxRQL-njd9Mv-C_lc/edit?usp=sharing
This should return two separate tabs/sheets based on room .
I am obviously not a programmer and do not know Visual Basic or Java or anything. I just know how to google and copy things....amazingly I often get it to work.
Let me know what else you need if you can help.
Try the below code:
'splitSheetIntoTabs' will split your master sheet in to separate sheets of 30 rows each. It will copy only the content not the background colors etc.
'deleteTabsOtherThanMaster' will revert the change done by 'splitSheetIntoTabs'. This function will help to revert the changes done by splitSheetIntoTabs.
function splitSheetIntoTabs() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var header = rows[0];
var contents = rows.slice(1);
var totalRowsPerSheet = 30; // This value will change no of rows per sheet
//below we are chunking the toltal row we have into 30 rows each
var contentRowsPerSheet = contents.map( function(e,i){
return i%totalRowsPerSheet===0 ? contents.slice(i,i+totalRowsPerSheet) : null;
}).filter(function(e){ return e; });
contentRowsPerSheet.forEach(function(e){
//crate new sheet here
var currSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet();
//append the header
currSheet.appendRow(header);
//populate the rows
e.forEach(function(val){
currSheet.appendRow(val);
});
});
}
// use this function revert the sheets create by splitSheetIntoTabs()
function deleteTabsOtherThanMaster() {
var sheetNotToDelete ='Master';
var ss = SpreadsheetApp.getActive();
ss.getSheets().forEach(function(sheet){
if(sheet.getSheetName()!== sheetNotToDelete)
{
ss.deleteSheet(sheet);
}
});
}
I was using Kessy's nice script, but started having trouble when the data became very large, where the script timed out. I started looking for ways to reduce the amount of times the script read/wrote to the spreadsheet (rather than read/write one row at a time) and found this post https://stackoverflow.com/a/42633934
Using this principle and changing the loop in the script to have a loop within the loop helped reduce these calls. This means you can also avoid the second call to append rows (the "else"). My script is a little different to the examples, but basically ends something like:
`for (var i = 1; i < theEmails.length; i++) {
//Ignore blank Emails and sheets created
if (theEmails[i][0] !== "" && !completedSheets.includes(theEmails[i][0])) {
//Set the Sheet name = email address. Index the sheets so they appear last.
var currentSheet = theWorkbook.insertSheet(theEmails[i][0],4+i);
//append the header
//To avoid pasting formulas, we have to paste contents
headerFormat.copyTo(currentSheet.getRange(1,1),{contentsOnly:true});
//Now here find all the rows containing the same email address and append them
var theNewRows =[];
var b=0;
for(var j = 1; j < rows.length; j++)
{
if(rows[j][0] == theEmails[i][0]) {
theNewRows[b]=[];//Initial new array
theNewRows[b].push(rows[j][0],rows[j][1],rows[j][2],rows[j][3],rows[j][4],rows[j][5],rows[j][6],rows[j][7]);
b++;
}
}var outrng = currentSheet.getRange(2,1,theNewRows.length,8); //Make the output range the same size as the output array
outrng.setValues(theNewRows);
I found a table of ~1000 rows timed out, but with the new script took 6.5 secs. It might not be very neat, as I only dabble in script, but perhaps it helps.
I have done this script that successfully gets each room and creates a new sheet with the corresponding room name and adding all the rows with the same room.
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
// This var will contain all the values from column C -> Room
var columnRoom = sheet.getRange("C:C").getValues();
// This var will contain all the rows
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
//Set the first row as the header
var header = rows[0];
//Store the rooms already created
var completedRooms = []
//The last created room
var last = columnRoom[1][0]
for (var i = 1; i < columnRoom.length; i++) {
//Check if the room is already done, if not go in and create the sheet
if(!completedRooms.includes(columnRoom[i][0])) {
//Set the Sheet name = room (except if there is no name, then = No Room)
if (columnRoom[i][0] === "") {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet("No Room");
} else {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(columnRoom[i][0]);
}
//append the header
currentSheet.appendRow(header);
currentSheet.appendRow(rows[i]);
completedRooms.push(columnRoom[i][0])
last = columnRoom[i][0]
} else if (last == columnRoom[i][0]) {
// If the room's sheet is created append the row to the sheet
var currentSheet = SpreadsheetApp.getActiveSpreadsheet()
currentSheet.appendRow(rows[i]);
}
}
}
Please test it and don't hesitate to comment for improvements.

Google Apps Script for Removing Rows Containing Part of a Keyword

I want to delete the rows on Google Sheets that contain employees, tests, irrelevant submissions, and duplicate entries. My code needs to be standalone so that it can be used across my workplace.
Specifically, I want to:
Remove any rows that contain an email address belonging to a certain organization (ex: any email address that ends in #domainname.com). I've been using a piece of code to delete rows containing three specific email addresses belonging to my coworkers, but I was hoping to find a way to delete all employees in one sweep without coding in each individual email. Here's the code I've been using:
function delVtlEm() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 0;
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
if (row[1] == 'isaac#domainname.com' ||
row[1] == 'danni#domainname.com' ||
row[1] == 'georgia#domainname.com') {
sheet.deleteRow((parseInt(i) + 1) - rowsDeleted);
rowsDeleted++;
}
}
}
Remove any rows that contain the word "login" from a comment section where "login" might be only part of the copy in that column. For example, someone might fill out a Contact Us form and ask in the comment section for help with their login info - but this isn't a qualified lead for my purposes. Their message may be "Hey, can you help me with my login?" or some other similar phrasing, which is why I want to delete any row containing "login" in any capacity.
Please let me know if you have any ideas or suggested code!
I have implemented the following smartDelete() function based on your code.
This function allows you to achieve the following,
Identify any number of domains (in badDomains array) to delete its corresponding rows.
Identify any number of words (in badWords array) to delete its corresponding rows.
Both of the two search criteria above are case-insensitive; you can change that by changing the regular expression modifier (stored in regExpModifiers) to "" or Null.
Actions above can be taken on three different columns (stored in fnameColumnNumber, emailColumnNumber and companyColumnNumber)
Let me know if you face any issues or have any feedback.
function smartDelete() {
// smartDelete settings goes here,
var badDomains = ["vtldesign\\.com", "parterreflooring\\.com"];
var badWords = ["Vital", "Parterre", "test"];
var fnameColumnNumber = 0;
var emailColumnNumber = 1;
var companyColumnNumber = 3;
var regExpModifiers = "i";
// Gain access data in the sheet
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 0;
var deleteAction = false;
// delete procedure
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
deleteAction = false;
// check bad words
for (var j = 0; j <= badWords.length - 1; j++) {
var myPattern = new RegExp(badWords[j], regExpModifiers);
var status = row[fnameColumnNumber].toString().match(myPattern);
if (status) {
// match found, mark this row for delete
deleteAction = true;
break;
};
};
// check bad domains
for (var j = 0; j <= badDomains.length - 1; j++) {
var myPattern = new RegExp(badDomains[j], regExpModifiers);
var status = row[emailColumnNumber].toString().match(myPattern);
if (status) {
// match found, mark this row for delete
deleteAction = true;
break;
};
};
// check bad words
for (var j = 0; j <= badWords.length - 1; j++) {
var myPattern = new RegExp(badWords[j], regExpModifiers);
var status = row[companyColumnNumber].toString().match(myPattern);
Logger.log(status)
if (status) {
// match found, mark this row for delete
deleteAction = true;
break;
};
};
// execute delete.
if (deleteAction) {
sheet.deleteRow((parseInt(i) + 1) - rowsDeleted);
rowsDeleted++;
};
};
}
You can use indexOf('what to find') to look for a partial string. Also, don't delete rows in the Sheet individually. That is inefficient. Delete elements (rows) from the array, clear the sheet tab, and then set all the new values.
function delVtlEm() {
var i,row;
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 0;
var arrayOfStringsToFind = ["whatToLookFor","whatToLookFor2","whatToLookFor3"];
for (i = 0; i <= numRows - 1; i++) {
row = values[i];
column1Value = row[0];//Get the value of column A for this row
column2Value = row[1];
column3Value = row[2];
if (arrayOfStringsToFind.indexOf('column1Value') !== -1) {
values.splice(i,1);//
}
if (column2Value.indexOf('#vtldesign.com') !== -1) {
values.splice(i,1);//Remove one element in the data array at index i
}
if (column3Value.indexOf('whatToLoookFor') !== -1) {
values.splice(i,1);//
}
}
sheet.clearContents();//clear the contents fo the sheet
sheet.getRange(1, 1, values.length, values[0].length);//Set new values
}

Creating a google form from a google spreadsheet

I have created a google spreadsheet to automatically convert into a google form, so i don't have to manually enter all the questions into the google form.
I am writing google app script and managed to get all the questions.I am trying to divide the form in to sections depending on the first column of the sheet. So if the first column is "1" questions corresponding to it should be on the first section and if it is "2" it should create another section.And so on.
How can i do that? what will be the code? I have attached the google sheet as here Google spreadsheet
function myFunction()
{
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var range = ss.getDataRange();
var data = range.getValues();
var numberRows = range.getNumRows();
var numberColumns = range.getNumColumns();
var firstRow = 1;
var form = FormApp.openById('1hIQCLT_JGLcvjz44vXTvP5ziia6NnwCqWBxYT4h2uCk');
var items = form.getItems();
var ilength = items.length;
for (var i=0; i<items.length; i++)
{
form.deleteItem(0);
}
for(var i=0;i<numberRows;i++)
{
Logger.log(data);
var questionType = data[i][0];
if (questionType=='')
{
continue;
}
//choose the type of question from the first column of the spreadsheet
else if(questionType=='1')
{
var rowLength = data[i].length;
var currentRow = firstRow+i;
var currentRangeValues = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(currentRow,1,1,rowLength).getValues();
var getSheetRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getDataRange();
var numberOfColumnsSheet = getSheetRange.getNumColumns();
var numberOfOptionsInCurrentRow = numberOfColumnsSheet;
var lastColumnInRange = String.fromCharCode(64 + (numberOfOptionsInCurrentRow));
var range_string = 'C' + currentRow + ":" + lastColumnInRange + currentRow;
var optionsArray = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(range_string).getValues();
var choicesForQuestion =[];
for (var j=0;j<optionsArray[0].length;j++)
{
choicesForQuestion.push(optionsArray[0][j]);
}
form.addMultipleChoiceItem().setTitle(data[i][1]).setHelpText("").setChoiceValues(choicesForQuestion).setRequired(true);
}
else
{
continue;
}
}
form.addParagraphTextItem()
.setTitle('Please specify and attach relevant documents'); // add the text question at the last
form.addPageBreakItem().setTitle('Identity - Asset Management').setHelpText("")();
}
googleSheet
If you want to use the same exact format for the next section you can get away with a simple counter. I have written a successful script variant, but it depends on what you really want.
Some of the changes I would do
for (i = 0; i < items.length; i++) {
form.deleteItem(items[i])
}
instead of the current form.deleteItem(0);. Otherwise I see that you grab all the data, however you do not utilize it. Calling the spreadsheet app each time you want the options causes it to run a lot slower. More on that for loop: move the Logger.log(data); outside of the loop. There is no reason for you to keep logging the full data range each time you go to the next row of the data. Or change it to Logger.log(data[i]); which would make more sense.
You already do a
if (questionType=='') {
continue;
}
to skip over the empty lines, so not really sure what that last else is meant for. The loop will fall through to the next option on its own anyway.
Now the way your set up would work is that your questions in the spreadsheet must be in order. That is you cannot have
Section 1
Section 2
Section 1
as that will create 3 sections instead of 2. However let's move along with the assumption that the spreadsheet would only be set up in a way where you will only have a sequence like
Section 1
Section 1
Section 2
In that case you should utilize your data and questionType by adding a counter var sectionCount = 0 somewhere before the loop. Then inside of your for loop you do a simple
else if (questionType != sectionCount) {
form.addSectionHeaderItem().setTitle('Section ' + questionType)
sectionCount++
}
this will create the section (provided that the numbers are always increasing by 1 in Column A). Then in the same for loop you do not need any more if statements and can just use
items = data[i].slice(2, data[i].length + 1)
items = items.filter(chkEmpty)
form.addMultipleChoiceItem().setTitle(data[i][1]).setChoiceValues(items)
where
function chkEmpty(val){
return val != ''
}
function myFunction()
{
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var ss2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet2');
var range = ss.getDataRange();
var data = range.getValues();
var numberRows = range.getNumRows();
var numberColumns = range.getNumColumns();
var firstRow = 1;
var form = FormApp.openById('1xlXDZB5jhbUWpWHxxJwY-ut5oYkh4OfIQSTGsnwGTW4');
var sectionCount = 0
// deletes the previous changes
var items = form.getItems();
var ilength = items.length;
for (i = 0; i < items.length; i++)
{
form.deleteItem(items[i])
}
for(var i=0;i<numberRows;i++)
{
var questionType = data[i][0];
if (questionType=='')
{
continue;
}
else if (questionType != sectionCount )
{
if (sectionCount != 0 )
{
// form.addParagraphTextItem()
// .setTitle('Please specify and attach relevant documents'); // add the text question at the last
// write the description here using SectionCount
}
sectionCount++ // add new section to the form
form.addSectionHeaderItem().setTitle('Section ' + questionType).setHelpText(""); // add section header and title
}
items = data[i].slice(2, data[i].length + 1)
items = items.filter(chkEmpty)
form.addMultipleChoiceItem().setTitle(data[i]
[1]).setChoiceValues(items).setRequired(true);
if ( i == (numberRows-1)){
// form.addParagraphTextItem()
// .setTitle('Please specify and attach relevant documents');
}
}
function chkEmpty(val)
{
return val != ''
}
Logger.log(data);
}