Invalid assignment left-hand side. (line 1, file "Code") after if statements are added - google-apps-script

The error "Invalid assignment left-hand side." only started to occur after the if statements are added.It used to be ok til i added the variables and if statements.
Tried using single '|' for or.
function auto() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var QA = ss.getSheetByName("Quality Alert");
var QAdata = QA.getRange(3,1,QA.getLastRow() - 2,29).getValues();
QAdata.forEach(function(row, i){
var customer = row[1] ;
var part = row[2] ;
var s = row[3] ;
var id = row[4] ;
var fid = row[5] ;
var defect = row[6] ;
var desc = row[7] ;
var reject1 = row[8] ;
var reject2 = row[9] ;
var ok = row[10] ;
var url = row[11] ;
var depart = row[12] ;
if( 0 < depart <= 7){
Part1.sendEmail()
}
if( depart = 8 ){
Part2.sendEmail()
}
if( depart = 9){
Part3.sendEmail()
}
if( depart = 10 || depart = 11){
Part4.sendEmail()
}
if( 10 < depart <= 15){
Part5.sendEmail()
}
});// End Bracket for QA Data
}
Expected result is when var depart (a number from 1 to 15) is entered, it will run a particular code from the library(PartN.sendEmail).

Fixed it by using "==" instead of "=".

Related

Google spreadsheet - script throws "Exceeded maximum execution time" error

I have the following google script that will run against 500+ rows of data in the "InputFromHospital" sheet and in the middle of execution, getting the "Exceeded maximum execution time" error.
I was having few more lines of code but after reading the similar questions in StackOverflow, I removed and kept only the needed lines/source code. I am not sure how I could further optimize.
Looking for your suggestions/expertise to optimize and to reduce the execution time to under 5 minutes?
function feedToMasterAndPolice() {
var ssbook = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = ssbook.getSheetByName('MasterPatientData')
var sLastRow = srcSheet.getLastRow() + 1
var inputSheet = ssbook.getSheetByName('InputFromHospital')
var iLastRow = inputSheet.getLastRow();
var pSheet = ssbook.getSheetByName('DataToPolice')
var pLastRow = pSheet.getLastRow() + 1;
var todayDate = Utilities.formatDate(new Date(), "IST", "dd/MMM/yyyy")
//Loop thru all rows in "Input.." sheet
for (var i = 2; i <= iLastRow; i++) {
//Reading contact number from "Input.." sheet
var value = inputSheet.getRange(i, 5).getValue();
var gID = "";
if (value.toString.length > 0) {
//Generating unique patient ID for each COVID Patient
gID = "PID".concat(srcSheet.getLastRow());
srcSheet.getRange(sLastRow, 1).setValue(gID.toString());
//Looping thru all 8 colums in "Input" sheet
for (var colN = 2; colN < 9; colN++) {
var actCellVal = inputSheet.getRange(i, colN).getValue();
//Set value for contact# and date values
if (colN == 5 || colN == 6 || colN == 8) {
srcSheet.getRange(sLastRow, colN).setValue(actCellVal)
} else {
//All String values - upper case
srcSheet.getRange(sLastRow, colN).setValue(actCellVal.toString().toUpperCase())
}
}
var cR = srcSheet.getLastRow();
//Adding formula to calculate "DAYS SINCE ADMISSION" - example =if(A2<>"",TODAY()-F2,"")
srcSheet.getRange(sLastRow, 9).setFormula("=if(A" + cR + "<>\"\",TODAY()-F" + cR + ",\"\")")
//Adding formula to calculate "FOLLOW UP NEEDED" - example =if(I2<=Admin!$C$2,"YES","NO"
srcSheet.getRange(sLastRow, 10).setFormula("=if(I" + cR + "<=\'Admin\'!$C$2,\"YES\",\"NO\")");
//Add current date
srcSheet.getRange(sLastRow, 11).setValue(todayDate);
sLastRow = sLastRow + 1
} else {
//Above logic same when contact number is blank
//Not considerd Patient ID #
var ppID = "NCPID".concat(pSheet.getLastRow());
//Untested
pSheet.getRange(pLastRow, 1).clear();
pSheet.getRange(pLastRow, 1).setValue(ppID.toString());
//till above
for (var colN = 2; colN <= 9; colN++) {
var actCellVal = inputSheet.getRange(i, colN).getValue();
if (colN == 6 || colN == 8) {
pSheet.getRange(pLastRow, colN).setValue(actCellVal)
} else {
pSheet.getRange(pLastRow, colN).setValue(actCellVal.toString().toUpperCase())
pSheet.getRange(pLastRow, 9).setValue(todayDate);
}
}
pLastRow = pLastRow + 1
}
}
//this.ClearAnySheet("InputFromHospital")
};
Sample file available here.
I believe your goal as follows.
You want to reduce the process cost of your script.
Modified script:
function feedToMasterAndPolice_b() {
var ssbook = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = ssbook.getSheetByName('MasterPatientData');
var sLastRow = srcSheet.getLastRow() + 1;
var inputSheet = ssbook.getSheetByName('InputFromHospital');
var pSheet = ssbook.getSheetByName('DataToPolice');
var pLastRow = pSheet.getLastRow() + 1;
var todayDate = Utilities.formatDate(new Date(), "IST", "dd/MMM/yyyy");
var [, ...values] = inputSheet.getDataRange().getValues();
var { masterPatientData, dataToPolice } = values.reduce((o, [c1, c2, c3, c4, c5, c6, c7, c8], i) => {
if (c5.toString() != "") {
var last = sLastRow - 1 + o.masterPatientData.length;
o.masterPatientData.push([
`PID${last}`,
...[c2, c3, c4, c5, c6, c7, c8].map((c, j) => [3, 4, 6].includes(j) ? c : c.toString().toUpperCase()),
`=if(A${last + 1}<>"",TODAY()-F${last + 1},"")`,
`=if(I${last + 1}<='Admin'!\$C\$2,"YES","NO")`,
todayDate,
]);
} else {
var last = pLastRow - 1 + o.dataToPolice.length;
o.dataToPolice.push([
`NCPID${last}`,
...[c2, c3, c4, c5, c6, c7, c8].map((c, j) => [4, 6].includes(j) ? c : c.toString().toUpperCase()),
todayDate,
]);
}
return o;
}, { masterPatientData: [], dataToPolice: [] });
if (masterPatientData.length > 0) {
srcSheet.getRange(sLastRow, 1, masterPatientData.length, masterPatientData[0].length).setValues(masterPatientData);
}
if (dataToPolice.length > 0) {
pSheet.getRange(pLastRow, 1, dataToPolice.length, dataToPolice[0].length).setValues(dataToPolice);
}
}
Note:
Unfortunately, I cannot test above modified script with your actual situation. So when my proposed script cannot be used for your actual situation, can you provide the sample Spreadsheet for replicating the issue? By this, I would like to confirm it.
References:
Benchmark: Reading and Writing Spreadsheet using Google Apps Script
getValues()
setValues(values)

"Lock wait timeout exceeded" when sending data from Google Sheets to MySQL

I wrote an Apps Script macro to send data from a Google spreadsheet to a MySQL table. In a first time, in delete some rows in the table and then I add rows in this table. I sometimes get a "Lock wait timeout exceeded; try restarting transaction" error. Sometimes it runs after 100 seconds, sometimes 4 minutes.
I don't understand what is wrong with this code.
//classeur.insertSheet("feuillebis")
//feuillebis=classeur.getSheets()[1]
//var feuillebis=classeur.getSheetByName('feuillebis')
var classeur = SpreadsheetApp.getActiveSpreadsheet() ;
var feuille = classeur.getActiveSheet();
var host = "107.167.186.180";
var databaseName = "eatology";
var userName = "root";
var password = "eatology";
var port = 3306;
var tableName = "weekly_order";
var url = 'jdbc:mysql://' + host + ':' + port + '/' + databaseName;
var nbrow = feuille.getMaxRows()
function Send_Weekly_Order_To_Data_Base() {
///here are all the connection parameters
var classeur = SpreadsheetApp.getActiveSpreadsheet();
var feuille = classeur.getActiveSheet();
var nbrow = feuille.getMaxRows();
var host = "107.167.186.180";
var databaseName = "eatology";
var userName = "root";
var password = "eatology";
var port = 3306;
var tableName = "weekly_order";
var url = 'jdbc:mysql://' + host + ':' + port + '/' + databaseName;
var conn = Jdbc.getConnection(url, userName, password);
conn.setAutoCommit(false);
///get the weekly_order as an array from the sql
var rowcount = 0;
var stmt2 = conn.createStatement();
var results = stmt2.executeQuery("SELECT * FROM eatology.weekly_order");
while (results.next()) {
if (results.getInt(1) > rowcount){
rowcount = results.getInt(1)
}
}
conn.commit();
results.close();
stmt2.close();
///delete the rows from the current week where we are running the macro
var timezone1 = classeur.getSpreadsheetTimeZone();
var date1 = Utilities.formatDate(feuille.getRange(2, 2).getValue(), timezone1, "yyyy-MM-dd");
var date2 = Utilities.formatDate(feuille.getRange(2, 3).getValue(), timezone1, "yyyy-MM-dd");
var date3 = Utilities.formatDate(feuille.getRange(2, 4).getValue(), timezone1, "yyyy-MM-dd");
var date4 = Utilities.formatDate(feuille.getRange(2, 5).getValue(), timezone1, "yyyy-MM-dd");
var date5 = Utilities.formatDate(feuille.getRange(2, 6).getValue(), timezone1, "yyyy-MM-dd");
var date6 = Utilities.formatDate(feuille.getRange(2, 7).getValue(), timezone1, "yyyy-MM-dd");
///clear the table weekly-order in the database
var stmt1 = conn.createStatement();
var result = stmt1.executeUpdate("DELETE FROM eatology.weekly_order where `Date` = " + "'" + date1 + "'" +" or `Date` = " + "'" + date2 + "'" +" or `Date` = " + "'" + date3 + "'" +" or `Date` = "+ "'" + date4 + "'" +" or `Date` = " + "'" + date5 + "'" +" or `Date` = "+ "'" + date6 + "'" );
//var result = stmt1.executeUpdate("DELETE FROM eatology.weekly_order where `Date` = " + "'" + date1 +"'");
conn.commit();
stmt1.close();
conn.close();
rowcount = rowcount + 1;
var conn = Jdbc.getConnection(url, userName, password);
conn.setAutoCommit(false);
var stmt = conn.prepareStatement('INSERT INTO eatology.weekly_order '
+ '(`Uid`, `Date`, `MP`, `Cname`, `Pname`, `Breakfast`, `Snack1`, `Lunch`, `Snack2`, `Dinner`) values (?,?,?,?,?,?,?,?,?,?)');
var program_name_line = 0;
var array = feuille.getRange(1, 1, nbrow, 7).getValues();
for (var j = 1; j < 7; j = j + 1) {
var inside = 0;
var i = 1;
while (array[i][0] != "Total" && i < 1000) {
i = i + 1
var color = feuille.getRange(i + 1, j + 1).getBackgrounds()
var fi1 = array[i][0].toString();
var fij = array[i][j].toString();
var empty = (fij == "");
var already = 0;
var test11111 = (color != "#5d31ce");
var cas1 = ((empty == false) && (fi1 != "Total") && (inside == 0));
var cas2 = (color == "#5d31ce" && inside == 1);
var cas3 = (empty == false);
if ((fi1 != "Total") && (inside == 0) && color != "#5d31ce") {
program_name_line = i;
inside = 1;
if (empty == false) {
var Uid = rowcount;
var Date1 = (Utilities.formatDate(array[1][j], timezone1, "yyyy-MM-dd"));
var MP = (array[program_name_line][0]);
var place = ((fij).indexOf("-"));
var length = (fij.length);
var Pname = ((fij).substring(place + 1, length));
var Cname = ((fij).substring(0, place));
var list = (meal(MP, Pname));
var Breakfast = list[0];
var Snack1 = list[1];
var Lunch = list[2];
var Snack2 = list[3];
var Dinner = list[4];
if (MP == "TM") {
var Breakfast = 1;
var Snack1 = 1;
var Lunch = 1;
var Snack2 = 1;
var Dinner = 1;
}
rowcount = rowcount + 1;
stmt.setInt(1, Uid);
stmt.setString(2, Date1);
stmt.setString(3, MP);
stmt.setString(4, Cname);
stmt.setString(5, Pname);
stmt.setInt(6, Breakfast);
stmt.setInt(7, Snack1);
stmt.setInt(8, Lunch);
stmt.setInt(9, Snack2);
stmt.setInt(10, Dinner);
stmt.addBatch();
}
}
else if (color == "#5d31ce" && inside == 1) {
inside = 0;
}
else if (empty == false && color != "#5d31ce") {
var Uid = rowcount ;
var Date1 = (Utilities.formatDate(array[1][j], timezone1, "yyyy-MM-dd"));
var MP = (array[program_name_line][0].toString());
var place = ((fij).indexOf("-"));
var length = (fij.length);
var Pname = ((fij).substring(place + 1, length));
var Cname = ((fij).substring(0, place));
var list = (meal(MP, Pname));
var Breakfast = (list[0]);
var Snack1 = (list[1]);
var Lunch = (list[2]);
var Snack2 = (list[3]);
var Dinner = (list[4]);
if (MP == "TM") {
var Breakfast = 1;
var Snack1 = 1;
var Lunch = 1;
var Snack2 = 1;
var Dinner = 1;
}
rowcount = rowcount+1;
stmt.setInt(1, Uid);
stmt.setString(2, Date1);
stmt.setString(3, MP);
stmt.setString(4, Cname);
stmt.setString(5, Pname);
stmt.setInt(6, Breakfast);
stmt.setInt(7, Snack1);
stmt.setInt(8, Lunch);
stmt.setInt(9, Snack2);
stmt.setInt(10, Dinner);
stmt.addBatch();
}
}
}
stmt.executeBatch();
conn.commit();
stmt.close();
conn.close();
}
function meal(MP, Pname){
var result= [0, 0, 0, 0, 0]
//in order to know if we have two snacks or only one because if the programm has more than 1200 cal, there are two snacks, otherwise, only one snack
var two_snacks = 1
if (MP.indexOf("1200") > -1) {
two_snacks = 0
}
//if the program type is '3'
if (Pname.indexOf("3") > -1) {
result[0] = 1;
result[1] = 1;
result[2] = 1;
result[4] = 1;
if (two_snacks == 1) {
result[3] = 1;
}
}
//if the program type is '2'
if (Pname.indexOf("2") > -1 && Pname.indexOf("S") == -1) {
result[0] = 1;
result[1] = 1;
result[2] = 1;
if (two_snacks == 1) {
result[3] = 1;
}
}
//if there is the B letter
if (Pname.indexOf("B") > -1) {
result[0] = 1;
}
//if there is the L letter
if (Pname.indexOf("L") > -1) {
result[2] = 1;
}
//if there is the D letter
if (Pname.indexOf("D") > -1) {
result[4] = 1;
}
//if there is the 2S letter
if (Pname.indexOf("2S") > -1) {
result[1] = 1;
result[3] = 1;
}
//if there is the 1S letter
if (Pname.indexOf("1S") > -1) {
result[1] = 1;
result[1] = 1;
}
return result
}

Google Sheet Script - Unsuccessful Email Automation

I'm trying to put together a script which cycles through a two dimensional range from a spreadsheet; when the criteria is met (in this case, when training is a month and a week respectively before needing renewed) an email should be sent.
I was able to achieve this when the script only had to cycle through one column with several rows; however now that I'm attempting to cycle through several columns and several rows, the script is running without error, but the data is not triggering an email to be sent.
A smaller version of the script I'm attempting to use is displayed below, though the original is much more extensive in an attempt to cover the large range of data. The script not present here is a repetition of the 'Column' sections for each individual column that needs to be taken into consideration.
function trainingReminder() {
//For testing purposes
//You can view the log by typing CMD+ENTER (CTRL + E) after you run the script.
Logger.log(msg);
// grab the Google Sheet object
var googleSheets = SpreadsheetApp.getActiveSpreadsheet();
// activates the first sheet
SpreadsheetApp.setActiveSheet(googleSheets.getSheets()[0]);
// grabs the sheet
var currentSheet = googleSheets.getActiveSheet();
// find the last row
var lastRow = currentSheet.getLastRow();
// The first row starts at row 2 to account for headers
var startRow = 2;
//**************************************************************//
// Column AU //
//**************************************************************//
// get AU column data (Training Name)
var range = currentSheet.getRange(2,48,lastRow-startRow+1,1 );
var numRows = range.getNumRows();
var remainingDays = range.getValues();
// get AR column data (Employee Names)
//range = currentSheet.getRange(2, 45, lastRow-startRow+1, 1);
var columnAR = range.getValues();
var warning_count = 0;
var msg = "";
// Loop column AU (Training Name) (1 Month)
for (var i = 0; i <= numRows - 1; i++) {
var daysLeft = remainingDays[i][0];
if(daysLeft == 30) {
// Checks to see if a cell value in column AU equals 30
var employeeName = columnAR[i][0];
msg = msg + "Don't Forget: "+employeeName+"'s "+employeeTraining+" is due in
"+daysLeft+" days.\n";
warning_count++;
}
}
// Loop column AU (Training Name) (1 Week)
for (var i = 0; i <= numRows - 1; i++) {
var daysLeft = remainingDays[i][0];
if(daysLeft == 7) {
// Checks to see if a cell value in column AU equals 7
var employeeName = columnAR[i][0];
var employeeTraining = range.getValue(1,48);
msg = msg + "Don't Forget: "+employeeName+"'s "+employeeTraining+" is due a week.\n";
warning_count++;
}
}
//**************************************************************//
// Column AV //
//**************************************************************//
// get AV column data (Training Name)
var range = currentSheet.getRange(2,49,lastRow-startRow+1,1 );
var numRows = range.getNumRows();
var remainingDays = range.getValues();
// get AR column data (Employee Names)
//range = currentSheet.getRange(2, 45, lastRow-startRow+1, 1);
var columnAR = range.getValues();
var warning_count = 0;
var msg = "";
// Loop column AV (Training Name) (1 Month)
for (var i = 0; i <= numRows - 1; i++) {
var daysLeft = remainingDays[i][0];
if(daysLeft == 30) {
// Checks to see if a cell value in column AV equals 30
var employeeName = columnAR[i][0];
var employeeTraining = range.getValue(1,49)
msg = msg + "Don't Forget: "+employeeName+"'s "+employeeTraining+" is due in "+daysLeft+" days.\n";
warning_count++;
}
}
// Loop column AV (Training Name) (1 Week)
for (var i = 0; i <= numRows - 1; i++) {
var daysLeft = remainingDays[i][0];
if(daysLeft == 7) {
// Checks to see if a cell value in column AV equals 7
var employeeName = columnAR[i][0];
var employeeTraining = range.getValue(1,49);
msg = msg + "Don't Forget: "+employeeName+"'s "+employeeTraining+" is due a week.\n";
warning_count++;
}
}
//**************************************************************//
// Column AW //
//**************************************************************//
// get AW column data (Training Name)
var range = currentSheet.getRange(2,50,lastRow-startRow+1,1 );
var numRows = range.getNumRows();
var remainingDays = range.getValues();
// get AR column data (Employee Names)
//range = currentSheet.getRange(2, 45, lastRow-startRow+1, 1);
var columnAR = range.getValues();
var warning_count = 0;
var msg = "";
// Loop column AW (Training Name) (1 Month)
for (var i = 0; i <= numRows - 1; i++) {
var daysLeft = remainingDays[i][0];
if(daysLeft == 30) {
// Checks to see if a cell value in column AW equals 30
var employeeName = columnAR[i][0];
var employeeTraining = range.getValue(1,50)
msg = msg + "Don't Forget: "+employeeName+"'s "+employeeTraining+" is due in "+daysLeft+" days.\n";
warning_count++;
}
}
// Loop column AW (Training Name) (1 Week)
for (var i = 0; i <= numRows - 1; i++) {
var daysLeft = remainingDays[i][0];
if(daysLeft == 7) {
// Checks to see if a cell value in column AW equals 7
var employeeName = columnAR[i][0];
var employeeTraining = range.getValue(1,50);
msg = msg + "Don't Forget: "+employeeName+"'s "+employeeTraining+" is due a week.\n";
warning_count++;
}
}
// Loop column CG (Training Name) (1 Week)
for (var i = 0; i <= numRows - 1; i++) {
var daysLeft = remainingDays[i][0];
if(daysLeft == 7) {
// Checks to see if a cell value in column CG equals 7
var employeeName = columnAR[i][0];
var employeeTraining = range.getValue(1,86);
msg = msg + "Don't Forget: "+employeeName+"'s "+employeeTraining+" is due a week.\n";
warning_count++;
}
}
if(warning_count) {
MailApp.sendEmail("example#email.com",
"Training Reminder", msg);
}
};
I realise there's probably something very obvious to anyone competent with writing scripts, but unfortunately I'm not there yet with it. Any help would be greatly appreciated!

MYSQL Join and create Distinct json

I have the following select
if ($result = $mysqli->query("SELECT
a.quoteID, a.quoteTitle , a.notes, c.web_path
FROM quotes a
INNER JOIN users_files b on b.user_id = a.quoteID
INNER JOIN files c on c.id = b.file_id ORDER BY quoteID ASC"))
{
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
which gets me information I need.
[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/23.pdf"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/22.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/21.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/20.jpeg"},{"quoteID":"2","quoteTitle":"Kaitlin","notes":"Smith","web_path":"\/surplusAdmin3\/upload\/24.jpg"},{"quoteID":"8","quoteTitle":"Bryar2","notes":"Long","web_path":"\/surplusAdmin3\/upload\/17.png"},{"quoteID":"11","quoteTitle":"Avram","notes":"Allison","web_path":"\/surplusAdmin3\/upload\/4.jpg"}]
I now need to get my result as:
[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path1":"\/surplusAdmin3\/upload\/23.pdf","web_path2":"\/surplusAdmin3\/upload\/22.jpeg","web_path3":"\/surplusAdmin3\/upload\/21.jpeg","web_path4":"\/surplusAdmin3\/upload\/20.jpeg"}]
I am not looking to re-do the MYSQL statement I just need to create a new array in the format I need.
I have the following code:
var currentQuoteID =0;
var dataChanged = [];
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
console.log(' current quote '+ currentQuoteID + ' = '+ e["quoteID"] + 'file count = '+ fileCount);
if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
else
{
console.log('just add the filename array Row = ' +arrayRow );
// need to insert to the array arrayRow
// dataChanged.push('web_path'+fileCount,e["web_path"]);
toPush = 'web_path'+fileCount+'"'+':'+'"'+ e["web_path"];
var field = 'web_path'+fileCount;
var data = e["web_path"];
var tempArray = [field,data];
dataChanged.push(toPush);
dataChanged.field = data;
//dataChanged = dataChanged.concat(tempArray);
fileCount = fileCount +1;
}
currentQuoteID = e["quoteID"];
console.log('stuff '+ JSON.stringify(dataChanged));
});
The result I am getting is :
dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image"},"web_path1","/surplusAdmin3/upload/22.jpeg"]
What I need is
dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image","web_path1","/surplusAdmin3/upload/22.jpeg"}]
But I cannot workout what I need to do here.
Got it working as follows:
// loop through and add field 'Type' can all be done in one loop.
dataReturned.forEach(function(e){
if (typeof e === "object" ){
e["Type"] = "other";
// console.log('stuff '+e['Type'][i] )
}
});
//loop through and workout the file type
dataReturned.forEach(function(e){
if (typeof e === "object" ){
var ext = e['web_path'].substr(e['web_path'].lastIndexOf('.') + 1);
if ( (ext === 'jpeg' ) || ( ext === 'jpg' )|| ( ext === 'png' )|| ( ext === 'gif' ) || ( ext === 'pdf' ))
{ e["Type"] = "image"; }
//console.log(e['web_path']);
// console.log('stuff '+ JSON.stringify(e))
}
});
// create a new array formated as needed
var currentQuoteID =0;
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
e["quoteID"] + 'file count = '+ fileCount);
if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
else
{
//console.log('just add the filename array Row = ' +arrayRow );
// need to insert to the array arrayRow
// dataChanged.push('web_path'+fileCount,e["web_path"]);
var field = 'web_path'+fileCount;
var data = webPath+e["web_path"];
var tempArray = [field,data];
dataChanged[arrayRow]['web_path'+fileCount] = data
fileCount = fileCount +1;
}
currentQuoteID = e["quoteID"];
console.log('stuff '+ JSON.stringify(dataChanged));
});

Losing importXML functions when running my current script

I am writing a Google script to copy values from a column of importXML data based on a certain date. Below is where I am currently, but the issue I am running into now is when the script is run it is removing the importXML formulas located in columnns G and H:
function moveValuesOnly2() {
var sheet = SpreadsheetApp.openById("0At2fAZApHI8adHJxWU5EVVBEbHd0YzA5UVBwOGQ3ZHc");
SpreadsheetApp.setActiveSpreadsheet(sheet);
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Dylan'))
var range= sheet.getRange("B3:AJ50");
var currentValue = range.getValues();
var COL_B = 0; // relative to col B
var COL_G = 5;
var COL_H = 6;
var COL_I = 7;
var COL_J = 8;
var COL_K = 9;
var COL_L = 10;
var COL_N = 12;
var COL_O = 13;
var COL_P = 14;
var COL_R = 16;
var COL_S = 17;
var COL_T = 18;
var COL_V = 20;
var COL_W = 21;
var COL_X = 22;
var COL_Z = 24;
var COL_AA = 25;
var COL_AB = 26;
var COL_AD = 28;
var COL_AE = 29;
var COL_AF = 30;
var COL_AH = 32;
var COL_AI = 33;
var COL_AJ = 34;
for(var i = 0 ; i < currentValue.length ; i++){
if (currentValue[i][0] == (1)) {
// Copy value at 0 days
currentValue[i][COL_J] = currentValue[i][COL_G];
currentValue[i][COL_K] = currentValue[i][COL_H];
currentValue[i][COL_L] = currentValue[i][COL_I];
}
for(var i = 0 ; i < currentValue.length ; i++){
if (currentValue[i][0] == (15)) {
// Copy value at 15 days
currentValue[i][COL_N] = currentValue[i][COL_G];
currentValue[i][COL_O] = currentValue[i][COL_H];
currentValue[i][COL_P] = currentValue[i][COL_I];
}
range.setValues(currentValue);
}
for(var i = 0 ; i < currentValue.length ; i++){
if (currentValue[i][0] == (30)) {
// Copy value at 30 days
currentValue[i][COL_R] = currentValue[i][COL_G];
currentValue[i][COL_S] = currentValue[i][COL_H];
currentValue[i][COL_T] = currentValue[i][COL_I];
}
range.setValues(currentValue);
}
for(var i = 0 ; i < currentValue.length ; i++){
if (currentValue[i][0] == (45)) {
// Copy value at 45 days
currentValue[i][COL_V] = currentValue[i][COL_G];
currentValue[i][COL_W] = currentValue[i][COL_H];
currentValue[i][COL_X] = currentValue[i][COL_I];
}
range.setValues(currentValue);
}
for(var i = 0 ; i < currentValue.length ; i++){
if (currentValue[i][0] == (60)) {
// Copy value at 60 days
currentValue[i][COL_Z] = currentValue[i][COL_G];
currentValue[i][COL_AA] = currentValue[i][COL_H];
currentValue[i][COL_AB] = currentValue[i][COL_I];
}
range.setValues(currentValue);
}
for(var i = 0 ; i < currentValue.length ; i++){
if (currentValue[i][0] == (75)) {
// Copy value at 75 days
currentValue[i][COL_AD] = currentValue[i][COL_G];
currentValue[i][COL_AE] = currentValue[i][COL_H];
currentValue[i][COL_AF] = currentValue[i][COL_I];
}
range.setValues(currentValue);
}
for(var i = 0 ; i < currentValue.length ; i++){
if (currentValue[i][0] == (90)) {
// Copy value at 90 days
currentValue[i][COL_AH] = currentValue[i][COL_G];
currentValue[i][COL_AI] = currentValue[i][COL_H];
currentValue[i][COL_AJ] = currentValue[i][COL_I];
}
range.setValues(currentValue);
}}}
Is there any way to prevent the ImportXML functions located in those columns from being lost each time the script is run. Also a huge thank you to user #Srik to getting to me to the point I am at!
I would think that the problem lies from the fact that you setValues on the range which includes your columns G & H.
The solution lies in using
var specialRange = sheet.getRange("G3:H50");
var formulas = specialRange.getFormulas();
at the begining of your script to save the formulas and then after your setValues call to use the following code
specialRange.setFormulas(formulas);
Let me know how that works for you.