How to solve a problem time expired in javasrcipt - javascript

I am trying to send data to Google Sheet in my mobile application.
The data arrives well but the code does not return the result quickly
here is my JavaScript code.
The problem is that it takes a long time (around 360s) to return the result
it's ok
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/177kUZc61U8huVsq2OcGsiF2OGdPCSxMjkoh2C4KIWPM/edit#gid=0");
var sheet = ss.getSheetByName('Info');
function doGet(e) {
var action = e.parameter.action;
if (action == 'UpdateInfo') {
//return UpdateInfo(e);
}
}
function doPost(e) {
var action = e.parameter.action;
if (action == 'UpdateInfo') {
return UpdateInfo(e);
}
}
function UpdateInfo(e) {
var values = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
var email = e.parameter.email;
var password = e.parameter.password;
//var date = sheet.getRange('A').getValues();//new Date();
var name = e.parameter.name; ///Item1
var lname = e.parameter.lname;
var itemuserImage = e.parameter.itemuserImage;
var region = e.parameter.region;
var provaince = e.parameter.provaince;
var ecole = e.parameter.ecole;
var Unite = e.parameter.unite;
var niveau = e.parameter.niveau;
//var flag = 0;
var lr = sheet.getLastRow();
for (var i = 1; i <= lr; i++) {
var IDuser = sheet.getRange(i, 1).getValue();
//row[1];
var shetemail=sheet.getRange(i,2).getValue();
var shetpassword=sheet.getRange(i,3).getValue();
if (shetpassword==password && shetemail==email ) {
sheet.getRange(i,4).setValue(name);
// sheet.getRange(i,5).setValue(lname);
//row[2];
///zoydghnmayad sheet.getRange(i,7).setValue(region);
//row[4];
sheet.getRange(i,8).setValue(provaince);
//row[5];
sheet.getRange(i,9).setValue(ecole);
//row[5];
sheet.getRange(i,10).setValue(Unite);
//row[5];
sheet.getRange(i,11).setValue(niveau);
//row[5];
var dropbox="USERSIMAGE prof";
var folder, folders=DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder=folders.next();
} else {
folder=DriveApp.createFolder(dropbox);
}
var fileName=IDuser+"profile_pic.jpg";
var contentType="image/jpg" , bytes=Utilities.base64Decode(itemuserImage), blob=Utilities.newBlob(bytes, contentType,fileName);
var file=folder.createFile(blob);
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK,DriveApp.Permission.VIEW);
var fileIdumage=file.getId();
var fileUrlumage="https://drive.google.com/uc?export=view&id=" +fileIdumage; sheet.getRange(i,6).setValue(fileUrlumage);
//row[5];
return ContentService.createTextOutput("its ok").setMimeType(ContentService.MimeType.TEXT);
}
} ///thiya loop
}

Not quite sure.But do you check your image size of "profile_pic.jpg".
In my experience,if you capture the profile image using mobile app camera,the image size is extremely large.It will take ages to upload the image if you forget to compress it(no need such high HD image for profile, and compression is neccesary).
As a matter of that,please double check size of the image you were uploading.And please do not forget to compress it if it occupy too much space.

Related

Script works in IE but not Chromium

I have a script I am using in a html file my program accesses. it has been using IE as the browser, but the new version no longer uses IE, it uses Chromium. some of the script works, but it gets to a point that it does nothing. no errors just stops. I am guessing there is a difference in the way Chromium handles the script. The script is one I got online and modified. I will include the code below. I use the update option the most "AutomateExcel3" please ignore my code block outs and comments as I was trying to figure sometime else out.
thanks for the help
<script>
//*********************************************INTRODUCTION*****************************************
//When using Web.Link the first thing to do is initialize what's called a handle to Pro/Engineer
// Get Session, Model.
var mGlob = pfcCreate("MpfcCOMGlobal");
var oSession = mGlob.GetProESession();
var CurDwg = oSession.CurrentModel;
var CurWind = oSession.CurrentWindow;
var Base = "P:\ENGINEERING FILES\TPS PRE-PROD ENG\MV-22\excel_file.xls";
function UpdateControls(Opt)
{
bottom.innerHTML = "";
var Cntls="";
if (Opt==1)
{
Cntls = "<H2>To Export:</H2>"+
"<LI>Enter target Excel Files path</LI><LI>Pick \"Dwg Table\"</LI><LI>Pick Drawing Table</LI><P><INPUT id=FileName type=file size=80 value=\""+Base+"\"><BR>"+
"<INPUT id=button1 type=button value=\"Dwg Table\" onclick=\"AutomateExcel1()\">";
}
else if (Opt==2)
{
Cntls = "<H2>To Import:</H2>"+
"<LI>Enter the Excel Files path</LI><LI>Pick \"Next>>>\"</LI><LI>Pick Drawing To Place</LI><P><INPUT id=FileName type=file size=80 value=\""+Base+"\"><BR>"+
"<INPUT id=button1 type=button value=\"Next>>>\" onclick=\"AutomateExcel2()\">";
}
else if (Opt ==3)
{
Cntls = "<H2>To Update:</H2>"+
"<LI>Enter the Excel Files path</LI><LI>Pick \"Dwg Table\"</LI><LI>Pick Drawing Table</LI><P><INPUT id=FileName type=file size=80 value=\""+Base+"\"><BR>"+
"<INPUT id=button1 type=button value=\"Dwg Table\" onclick=\"AutomateExcel3()\">";
}
middle.innerHTML = Cntls;
}
function AutomateExcel1()
{
var MultipleLinesInCells = false;
//Have the user pick a table to export
var SelOptions = pfcCreate("pfcSelectionOptions").Create ("dwg_table");
SelOptions.MaxNumSels = 1;
var Selections = oSession.Select(SelOptions, null);
var Table = Selections.Item(0).SelItem;
//Build a matrix containing the values for the table
var nTableRows = Table.GetRowCount();
var nTableCols = Table.GetColumnCount();
//Start a new Excel Spreadsheet
var oXL;
oXL = new ActiveXObject("Excel.Application");
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
//Loop around the table and dump information to excel
for (i=0;i<nTableRows;i++)
{
for (j=0;j<nTableCols;j++)
{
var Cell = pfcCreate("pfcTableCell").Create(i+1, j+1);
var Mode = pfcCreate("pfcParamMode").DWGTABLE_NORMAL;
try
{
var Val = Table.GetText (Cell,Mode);
var Out="";
if (Val.Count>1)
MultipleLinesInCells = true;
for (k=0;k<Val.Count;k++)
{
if (k>0)
{
if (k<Val.Count)
{
Out = Out + " ";
}
}
Out = Out + Val.Item(k);
}
oSheet.Cells(i+1, j+1).Value = Out;
}
catch(er)
{
//Failure occurs when cells are merged, pro/e doesn't recognize cells that are now merged into another
}
}
}
//Bring up Excel for user to do with what they want.
//oXL.Visible = true;
oXL.UserControl = false;
if (FileName.value==null)
File = Base
else
File = FileName.value;
try
{
oWB.Close(true, File,null);
oXL.Workbooks.Close();
oXL.Quit();
Base = FileName.value;
var Out = "<H2>Success:</H2>Pick here for created document";
if (MultipleLinesInCells)
Out = Out + "<H2>Warning:</H2>The export resulted in some Multi-line cells being concatenated";
bottom.innerHTML = Out;
}
catch(er)
{
var Out = "<H2>Error:</H2>Could Not Write Specified File, please edit path and try again. If not Chuck Norris Might Get Angry!";
bottom.innerHTML = Out;
}
}
function AutomateExcel2()
{
//Have the user pick somewhere
var mousePick = oSession.UIGetNextMousePick ( pfcCreate("pfcMouseButton").MOUSE_BTN_LEFT);
var Orig = mousePick.Position;
//Start Excel
var oXL = new ActiveXObject("Excel.Application");
try
{
var oWB = oXL.Workbooks.Open(FileName.value);
var oSheet = oWB.ActiveSheet;
Base = FileName.value;
}
catch (er)
{
bottom.innerHTML = "<H2>Error:</H2>Could Not Open Specified File, \""+FileName.value+"\" for Import, please edit path and try again";
return;
}
//Start the table instructions
var TableInsts = pfcCreate("pfcTableCreateInstructions").Create (Orig);
var TableSizeType = pfcCreate("pfcTableSizeType").TABLESIZE_BY_NUM_CHARS;
TableInsts.SizeType = TableSizeType;
var columnInfo = pfcCreate ("pfcColumnCreateOptions");
//Look for headers in top row
var nCols=0;
var Val = oSheet.Cells(1,nCols+1).Value;
while (Val!=null)
{
nCols=nCols+1;
Val = oSheet.Cells(1,nCols+1).Value;
var column = pfcCreate ("pfcColumnCreateOption").Create (pfcCreate ("pfcColumnJustification").COL_JUSTIFY_LEFT,Math.round(oSheet.Cells(1,nCols).ColumnWidth+1));
columnInfo.Append (column);
}
//Push column information into Table Instructions
TableInsts.ColumnData = columnInfo;
//Push in the Header row
var rowInfo = pfcCreate ("realseq");
rowInfo.Append (2.0); //title line
TableInsts.RowHeights = rowInfo;
//Now create the table in proe
var CurTable = CurDwg.CreateTable(TableInsts);
//Populate the header information
for (var i=1;i<=nCols;i++)
{
var Val = oSheet.Cells(1,i).Value;
writeTextInCell (CurTable, 1, i, Val);
}
//Populate the rest of the table
var i=2;
var Row = oSheet.Cells(i,1).Value;
while (Row!=null)
{
CurTable.InsertRow (1.0, i-1, false);
for (var j=1;j<=nCols;j++)
{
var Val = oSheet.Cells(i,j).Value;
writeTextInCell (CurTable, i, j, Val);
}
i=i+1;
Row = oSheet.Cells(i,1).Value;
}
//Close down Excel.
oXL.UserControl = false;
oWB.Close(true);
oXL.Workbooks.Close();
oXL.Quit();
Excel.Application.Quit(); // added this to try to close excel
var Out = "<H2>Success:</H2>Excel sheet imported as Pro/E Drawing Table";
bottom.innerHTML = Out;
}
function AutomateExcel3()
{
//Have the user pick a table to update
var SelOptions = pfcCreate("pfcSelectionOptions").Create ("dwg_table");
SelOptions.MaxNumSels = 1;
var Selections = oSession.Select(SelOptions, null);
var Table = Selections.Item(0).SelItem;
//Start Excel
var oXL = new ActiveXObject("Excel.Application");
try
{
var oWB = oXL.Workbooks.Open(FileName.value);
var oSheet = oWB.ActiveSheet;
Base = FileName.value;
}
catch(er)
{
bottom.innerHTML = "<H2>Error:</H2>Could Not Open Specified File, \""+FileName.value+"\" for Update, please edit path and try again.";
return;
}
//Look for headers in top row and check them against the already existing headers
var nProCols = Table.GetColumnCount ();
var nCols=0;
var Val = oSheet.Cells(1,nCols+1).Value;
while (Val!=null)
{
nCols=nCols+2; // default was 1 changed to 2 now it doesn't delete the column if nothing in the first row.
//Check to see if we need to add another column
if (nCols>nProCols)
{
Table.InsertColumn (Math.round(oSheet.Cells(1,nCols).ColumnWidth+1), nCols-1, false);
nProCols=nProCols+1;
}
//Get current XL value
var ValXL = oSheet.Cells(1,nCols).Value;
//Get current ProE value
var cell = pfcCreate ("pfcTableCell").Create (1, nCols);
var mode = pfcCreate("pfcParamMode").DWGTABLE_NORMAL;
try
{
var ValProE = Table.GetText (cell, mode).Item(0);
}
catch(er)
{
var ValProE = "";
}
//Overwrite ProE value with XL value if they are not equal
if (ValProE!=ValXL)
{
ModifyCellText(Table, cell, ValXL);
}
Val = oSheet.Cells(1,nCols+1).Value;
}
//Check to see if any columns are left that need deleting off
//removed code and it appears to work without setting column to 15 above
while (nCols<nProCols)
{
Table.DeleteColumn (nProCols, false);
nProCols=nProCols-1; //default was -1 (changed to -0 and crashed creo)
}
//Populate the rest of the table
var nProRows = Table.GetRowCount();
var nRows = 0;
var Val = oSheet.Cells(nRows+1,1).Value;
while (Val!=null)
{
nRows = nRows + 1;
//Check to see if we need to add another row
if (nRows>nProRows)
{
Table.InsertRow (1, nRows-1, false);
nProRows=nProRows+1;
}
//Loop around all columns for each row
for (i=1;i<=nCols;i++)
{
//Get current XL value
var ValXL = oSheet.Cells(nRows,i).Value;
//Get current ProE value
var cell = pfcCreate ("pfcTableCell").Create (nRows, i);
var mode = pfcCreate("pfcParamMode").DWGTABLE_NORMAL;
try
{
var ValProE = Table.GetText (cell, mode).Item(0);
}
catch(er)
{
var ValProE = "";
}
//Overwrite ProE value with XL value if they are not equal
if (ValProE!=ValXL)
{
ModifyCellText(Table, cell, ValXL);
}
}
Val = oSheet.Cells(nRows+1,1).Value;
}
//Check to see if any rows are left that need deleting off
while (nRows<nProRows)
{
Table.DeleteRow (nProRows, false);
nProRows=nProRows-1;
}
CurDwg.Regenerate ();
//Close down Excel.
oXL.DisplayAlerts = false;
oXL.UserControl = false;
oWB.Close(true);
oXL.Workbooks.Close();
oXL.Quit();
// below code seams to stop excel instance created by from task manager while leaving other instances of excel alone
excel = null;
excelfile = null;
excelsheet = null;
CollectGarbage();
setTimeout("CollectGarbage()",1);
oSheet = null;
oWB = null;
oXL = null;
// below code kills excel from taskmanager but all excel is closed.
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("taskkill /F /IM EXCEL.exe");
CurDwg.UpdateTables ();
var Out = "<H2>Success:</H2>Excel sheet used as basis to update a Pro/E Drawing Table"+
"<p>Note:"+
"<LI>Cell Font and Alignment is Maintained for existing cells</LI>"+
"<LI>Rows can be added and removed - this is likely to require extra formatting</LI>"+
"<LI>There may be problems involving updating tables with merged cells</LI>"+
"<LI>Ensure you check the table for correct format after an update</LI>"+
"<LI>Congratulations Chuck Norris Approves!</LI>"+
"</p>";
bottom.innerHTML = Out;
}
function ModifyCellText(Table, cell, ValXL)
{
try
{
var CellNote = Table.GetCellNote (cell);
var CellNoteInsts = CellNote.GetInstructions (true);
var CellNoteTextLines = CellNoteInsts.TextLines;
var CellNoteTextLine1 = CellNoteInsts.TextLines.Item(0);
var CellNoteTextLine1Texts = CellNoteTextLine1.Texts;
var CellNoteTextLine1Text1 = CellNoteTextLine1Texts.Item(0);
var FontName = CellNoteTextLine1Text1.FontName;
}
catch(er)
{
var FontName = "ariallight.TTF";
}
var lines = pfcCreate("stringseq");
lines.Append (ValXL);
Table.SetText(cell, lines);
var CellNote = Table.GetCellNote (cell);
var CellNoteInsts = CellNote.GetInstructions (true);
var CellNoteTextLines = CellNoteInsts.TextLines;
var CellNoteTextLine1 = CellNoteInsts.TextLines.Item(0);
var CellNoteTextLine1Texts = CellNoteTextLine1.Texts;
var CellNoteTextLine1Text1 = CellNoteTextLine1Texts.Item(0);
//Switch Font
CellNoteTextLine1Text1.FontName = FontName;
CellNote.Modify (CellNoteInsts);
}
function writeTextInCell(table /* pfcTable */, row /* integer */,
col /* integer */, text /* string */)
{
var cell = pfcCreate ("pfcTableCell").Create (row, col);
var lines = pfcCreate ("stringseq");
lines.Append (text);
try{
table.SetText (cell, lines);
}
catch(er)
{
alert (row+" "+col);
}
}
// Function to create the activeX objects that are the interface to Web.Link.
function pfcCreate (className)
{
if (!pfcIsWindows())
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
if (pfcIsWindows())
return new ActiveXObject ("pfc."+className);
else
{
ret = Components.classes ["#ptc.com/pfc/" + className + ";1"].createInstance();
return ret;
}
}
//Checks what OS is being operated
//IE11 requires more indepth browser testing...
function get_browser_info(){
var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem=/\brv[ :]+(\d+)/g.exec(ua) || [];
return {name:'IE',version:(tem[1]||'')};
}
if(M[1]==='Chrome'){
tem=ua.match(/\bOPR\/(\d+)/)
if(tem!=null) {return {name:'Opera', version:tem[1]};}
}
M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
return {
name: M[0],
version: M[1]
};
}
function pfcIsWindows ()
{
var browser = get_browser_info();
if (browser.name.indexOf ("IE") != -1)
return true;
else
return false;
}
</script>
code worked perfectly in IE but not in the new browser I am forced to use

Filter CVS before importing to Google Spreadsheet

I have a Script in a Google Spreadsheet, the script downloads a zipped CSV from an URL and then import it to the spreadsheet. Actually, the CVS is too big and I don't need all the data from it. My question is, How can I filter the data before importing it to the spreadsheet? For example filter Column A with X value.
This is the code I have so far:
function descargarzip()
{
var urldescarga = "http://187.191.75.115/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip"
var url = urldescarga
var zipblob = UrlFetchApp.fetch(url).getBlob();
zipblob.setContentTypeFromExtension();
var unzipblob = Utilities.unzip(zipblob);
var unzipstr=unzipblob[0].getDataAsString();
var csv = Utilities.parseCsv(unzipstr);
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
ss.getRange(1, 1, csv.length, csv[0].length).setValues(csv);
}
Thank you in advance!
Try this:
function descargarzip() {
var urldescarga = "http://187.191.75.115/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip"
var url = urldescarga
var zipblob = UrlFetchApp.fetch(url).getBlob();
zipblob.setContentTypeFromExtension();
var unzipblob = Utilities.unzip(zipblob);
var unzipstr=unzipblob[0].getDataAsString();
var csv = Utilities.parseCsv(unzipstr);
var x = 'You enter the contents x';
csv.forEach(function(r,i){
if(r[0]==x) {
r[0]='';//You have to put something back in there because the csv has to be a rectangular array for setValues();
}
});//You could remove an entire line or an entire column
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
ss.getRange(1, 1, csv.length, csv[0].length).setValues(csv);
}
If #TheMaster is correct then try this:
function descargarzip() {
var urldescarga = "http://187.191.75.115/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip"
var url = urldescarga
var zipblob = UrlFetchApp.fetch(url).getBlob();
zipblob.setContentTypeFromExtension();
var unzipblob = Utilities.unzip(zipblob);
var unzipstr=unzipblob[0].getDataAsString();
var csv = Utilities.parseCsv(unzipstr);
var x = 'You enter the contents x';
var d=0;
//I tested this on some of my data and I believe it works
for(var i=0;(i-d)<csv.length;i++) {
if(csv[i-d][0]==x) {
csv.splice(i-d++,1);//I think this is correct but I could be wrong in here because I mostly use this approach for deleting rows not portions of the array. So if you have problems the please share your csv data and I will debug it.
}
}
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
ss.getRange(1, 1, csv.length, csv[0].length).setValues(csv);
}

Prevent google script from duplicating protected ranges

I have this script that I am using to copy over (convert formulas to values) and then protect the range when a user enters a value "Burned" in to a certain cell (A2, A6, etc) at the end of each month (can't make it triggered by date as users may be completing data entry on slightly different dates). The spreadsheet needs users to lock the data every month, so the script is set up for converting and protecting data each month as the user enters "Burned" into each month. The script is working well to convert formulas to values and it is also working to protect the range. However, every time I edit the sheet, it creates duplicate protected ranges so I end up with multiple protected ranges called January Burned, February Burned, etc. Is there any way to prevent the script from duplicating the protected ranges? Any help is greatly appreciated.
function onEdit(e)
//January
{
var ss = SpreadsheetApp.getActive();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Caseload");
var valueToCheckA = sheet.getRange("A2").getValue();
var rangeA = sheet.getRange("A2:AZ5");
{
if(valueToCheckA == "Burned")
{
rangeA.copyTo(rangeA, {contentsOnly:true});
var protection = rangeA.protect().setWarningOnly(true).setDescription('January Burned');
}
}
}
//February
{
var ss = SpreadsheetApp.getActive();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Caseload");
var valueToCheckB = sheet.getRange("A6").getValue();
var rangeB = sheet.getRange("A6:AZ9");
{
if(valueToCheckB == "Burned")
{
rangeB.copyTo(rangeB, {contentsOnly:true});
var protection = rangeB.protect().setWarningOnly(true).setDescription('February Burned');
}
}
}
//March
{
var ss = SpreadsheetApp.getActive();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Caseload");
var valueToCheckC = sheet.getRange("A10").getValue();
var rangeC = sheet.getRange("A10:AZ13");
{
if(valueToCheckC == "Burned")
{
rangeC.copyTo(rangeC, {contentsOnly:true});
var protection = rangeC.protect().setWarningOnly(true).setDescription('March Burned');
}
}
}
You had some weird things going on in your code. So I'd reformat it like this:
//January
function onEdit(e)
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Caseload");
var valueToCheckA = sheet.getRange("A2").getValue();
var rangeA = sheet.getRange("A2:AZ5");
if(valueToCheckA == "Burned")
{
rangeA.copyTo(rangeA, {contentsOnly:true});
var protection = rangeA.protect().setWarningOnly(true).setDescription('January Burned');
}
}
Try it again and let me know if anything has changed.
After looking over you code again. I grabbed entire code and took a close look at it and I made an interesting discovery. Several of your sections of code are not within the function onEdit so they run every time you access your scripts even when onEdit is not called. In fact, when I think about it, I believe you just run this once a month so why not just put it in a separate function and call once a month and forget the onEdit trigger.
function onEdit(e)
{
var ss = SpreadsheetApp.getActive();//January
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Caseload");
var valueToCheckA = sheet.getRange("A2").getValue();
var rangeA = sheet.getRange("A2:AZ5");
if(valueToCheckA == "Burned")
{
rangeA.copyTo(rangeA, {contentsOnly:true});
var protection = rangeA.protect().setWarningOnly(true).setDescription('January Burned');
}
}
// This section is not in the onEdit function so it's run every time you come to this page
var ss = SpreadsheetApp.getActive();//February
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Caseload");
var valueToCheckB = sheet.getRange("A6").getValue();
var rangeB = sheet.getRange("A6:AZ9");
if(valueToCheckB == "Burned")
{
rangeB.copyTo(rangeB, {contentsOnly:true});
var protection = rangeB.protect().setWarningOnly(true).setDescription('February Burned');
}
// This section is not in the onEdit function so it's run every time you come to this page
var ss = SpreadsheetApp.getActive();//March
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Caseload");
var valueToCheckC = sheet.getRange("A10").getValue();
var rangeC = sheet.getRange("A10:AZ13");
if(valueToCheckC == "Burned")
{
rangeC.copyTo(rangeC, {contentsOnly:true});
var protection = rangeC.protect().setWarningOnly(true).setDescription('March Burned');
}
So here's a rough start of a function that could do the job for you and you can just run it once a month. I haven't tested it and it most likely has some mistakes in it so check it out.
function monthlyBurn()
{
var ui = SpreadsheetApp.getUi();
var response = ui.prompt('Enter checkCell,protectRange,description all separate by commas', ui.ButtonSet.OK);
var t = response.getResponseText().split(',');
if(t.length !== 3)
{
ui.alert('Invalid input. Your missing a parameter')
return;
}
var ss = SpreadsheetApp.getActive();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Caseload");
var valueToCheckC = sheet.getRange(t[0]).getValue();
var rangeC = sheet.getRange(t[1]);
if(valueToCheckC == "Burned")
{
rangeC.copyTo(rangeC, {contentsOnly:true});
var protection = rangeC.protect().setWarningOnly(true).setDescription(t[2]);
}
}
Thanks for all the input and assistance, I have spoken with a colleague who was able to write this script which is working great.
function onEdit(e)
{
var sheet = e.range.getSheet();
if (sheet.getName() != "Caseload" || e.value != "Burned") return;
var moment = Moment.load();
var date = moment.utc(e.range.offset(0, 1).getValue());
if (!date.isValid()) return;
var month = date.format('MMMM');
var range = sheet.getRange(e.range.getRow(), e.range.getColumn(), 4, 26*2); // 4 rows and 26*2 columns (AZ)
range.copyTo(range, {contentsOnly: true});
range.protect().setWarningOnly(true).setDescription(month + ' Burned');

sending data from a google spreadsheet program to google calender

Here is my case.
A user fills a form for event booking, the submitted form is stored in a google spreadsheet which I have synced to a google calender so that it automatically sends the data to it.
Everything is working fine apart from the fact that event times could clash.
When customers book an event centre for let's say on 13/3/2015 T 10:00AM, if another user enters the same date and time, the entry should not be accepted.
To summarise it, I want to avoid a clash of events booking. Thank you all.
here is my script.
var calendarId = "mycalenderid";
//below are the column ids of that represents the values used in the spreadsheet (these are non zero indexed)
var startDtId = 9;
var endDtId = 10;
var titleId = 6;
var descId = 11;
var formTimeStampId = 1;
function getLatestAndSubmitToCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();
var startDt = sheet.getRange(lr,startDtId,1,1).getValue();
//set to first hour and minute of the day.
//startDt.setHours(0);
//startDt.setMinutes(00);
var endDt = sheet.getRange(lr,endDtId,1,1).getValue();
//set endDt to last hour and minute of the day
//endDt.setHours(23);
//endDt.setMinutes(59);
var subOn = "Submitted on:"+sheet.getRange(lr,formTimeStampId,1,1).getValue();
var desc = "Added by :"+sheet.getRange(lr,descId,1,1).getValue()+"\n"+subOn;
var title = sheet.getRange(lr,titleId,1,1).getValue()+"DIA";
createEvent(calendarId,title,startDt,endDt,desc);
}
function createEvent(calendarId,title,startDt,endDt,desc) {
var cal = CalendarApp.getCalendarById(calendarId);
var start = new Date(startDt);
var end = new Date(endDt);
var loc = 'Script Center';
var event = cal.createEvent(title, start, end, {
description : desc,
location : loc
});
};
Here's a pseudocode of what you're trying to do:
function findEvent(desiredDateTime)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var range = sheet.getDataRange();
var data = range.getValues();
var lRow = range.getLastRow();
var flag = true;
var count = 0;
while (flag == true || count < lRow)
{
if (desiredDateTime >= data[count][startDtId] && desiredDateTime <= data[count][endDtId])
{
flag = false;
}
else
{
count++;
}
}
if (flag == true)
{
//Call function to add event
}else{
//Tell user desired date-time is not available.
//If you're asking for user's email address,
//simplest approach would be to send an email.
}
}
You might have to modify other bits and pieces of your code as well to accommodate this but it shouldn't be too hard. Hope this provides you with a certain direction to follow through.

Compare value to another spreadsheet using array loop and write new values

Hello all I'm having trouble implementing array loops in my project... Here is what I want to do.
I have a spreadsheet called "Red Book" this sheet gets updated regularly once the staff have updated it I have a column where they can select to submit the data they've just entered on that specific row (editing this column calls an onEdit function).
The data will then be written to another spreadsheet (different file) called "Raw Data"
For each submit I have a unique identifier. I need the onEdit code to do the following...
Iterate through the column A to find the unique identifier
Once found update the data in columns 1 through 5
Below is the script I have so far:
function TransferToAppData(e) {
var destFile = SpreadsheetApp.openById('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
var destSheet = destFile.getSheetByName("Raw App Data");
var ss = e.source;
var s = ss.getActiveSheet();
var uniConstRng = s.getRange("A1");
var uniqueConstVal = uniConstRng.getValue();
var NextOpenRow = destSheet.getLastRow() + 1;
var ActiveRow = e.range.getRow();
Logger.log(ActiveRow);
var uniqueVal = s.getRange(ActiveRow,1).getValue();
var add = s.getRange(ActiveRow,2).getValue();
var name = s.getRange(ActiveRow,3).getValue();
var dt = s.getRange(ActiveRow,5).getValue()
if (uniqueVal == "") {
s.getRange(ActiveRow,1).setValue(uniqueVal + 1);
uniConstRng.setValue(uniqueVal + 1);
var transferVals = s.getRange(ActiveRow,1,1,5).getValues();
Logger.log(transferVals);
destSheet.getRange(NextOpenRow,1,1,5).setValues(transferVals);
destSheet.getRange(NextOpenRow, 6).setValue("Applicant");
}
else {
var destLastRow = destSheet.getLastRow();
var destDataRng = destSheet.getRange(2,1,destLastRow,5)
var destValues = destDataRng.getValues();
var sourceValues = s.getRange(ActiveRow,1,1,5).getValues();
for( var i = 0; i < destValues.length; ++i){
if (destValues([i][0])==uniqueVal) {
for(n=0;n<destValues[0].length;++n){
///I"m stuck!!!
}
}
}
}
}
As you can see I have the first array loop going, but I'm having trouble figuring out how to do a second loop that iterates only on the row where the unique value is found and write the source data to ONLY to row where the unique value was found not the whole sheet.
I figured it out...
Below is the code and here is how it works...
When values in certain columns are edited this code is fired.
1--It finds the unique identifier located in the row which was edited.
2--Compares that identifier with a column of unique identifiers in another spreadsheet.
3--When a match is found it writes the change to the new spreadsheet and exits the loop
function TransferToAppData(e) {
var destFile = SpreadsheetApp.openById('1V3R2RnpA8yXmz_JDZSkBsK9tGR2LjHZp52p5I1CuQvw');
var destSheet = destFile.getSheetByName("Raw App Data");
var ss = e.source;
var s = ss.getActiveSheet();
var uniqueConstRng = s.getRange("A1");
var uniqueConstVal = uniqueConstRng.getValue();
var NextOpenRow = destSheet.getLastRow() + 1;
var ActiveRow = e.range.getRow();
var uniqueVal = s.getRange(ActiveRow,1).getValue();
if (s.getRange(ActiveRow,2).getValue() == "" || s.getRange(ActiveRow,3).getValue()=="" || s.getRange(ActiveRow,4).getValue()=="" || s.getRange(ActiveRow,5).getValue()=="") {
s.getRange(ActiveRow,13).clearContent();
Browser.msgBox("Address, Name, Date Entered & Rent are required fields!");
} else{
if (uniqueVal == "") {
s.getRange(ActiveRow,1).setValue(uniqueConstVal + 1);
uniqueConstRng.setValue(uniqueConstVal + 1);
var transferVals = s.getSheetValues(ActiveRow,1,1,5);
destSheet.getRange(NextOpenRow,1,1,5).setValues(transferVals);
destSheet.getRange(NextOpenRow, 6).setValue("Applicant");
}
else {
var destLastRow = destSheet.getLastRow();
var destValues = destSheet.getSheetValues(2,1,destLastRow,5);
var sourceValues = s.getSheetValues(ActiveRow,1,1,5);
for(var i = 0; i < destValues.length; ++i){
if (destValues[i][0]===uniqueVal) {
destSheet.getRange(i+2,1,1,5).setValues(sourceValues);
break;
}
}
}
s.sort(1,false);
destSheet.sort(1,false);
}
}

Categories

Resources