I need help with the javascript code for the following:
I created a .pdf order form. The first field on the form is the order number.
I would like to generate the order number automatically each time the .pdf file is opened. As well, I want it to increment by 1 starting from the number 1001 each time the order form is opened.
I've stored the numeric value 1001 in cell(1,1) of an excel file.
I want create a javascript to extract (Read) the current value in cell(1,1) and return that data to me.
In addition, I want the same script to overwrite the current value in cell(1,1) with value + 1.
I have searched the internet extensively and found several bits of code but none of them produce the results that I want. maybe I am doing something wrong. Help please! Below is the code I have for starters. As my programming skills are not great, I have not even certain how to incorporate the Write code. Many thanks for your help.
function readfile(){
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("C:\Document and Settings\User\Desktop\ORDNO.xlsx");
var excel_sheet = excel_file.Worksheets("Sheet1");
var data = excel_sheet.Cells(1,1).Value = OrdNo;
return data;
}
event.value = Ordno
Excel.Quit();
Related
I have a simple script to generate a doc and PDF upon form submission. It worked well on simple template (e.g. Only 1 sentence, First name, Last name and Company name).
However, when I use a template that's longer, having many fields, and formatting, the code runs but replace the text randomly.
I have tried to hardcode the fields of forms in ascending order as the doc template. However it still replace the text randomly
Can anybody points out what have I done wrong?
My code:
function myFunction(e) {
var response = e.response;
var timestamp = response.getTimestamp();
var [companyName, country, totalEmployees,totalPctWomenEmployees,numberNationality,name1,position1,emailAdd1,linkedin1,funFact1,name2,position2,emailAdd2,linkedin2,gameStage,gameStory] = response.getItemResponses().map(function(f) {return f.getResponse()});
var file = DriveApp.getFileById('XXXXX');
var folder = DriveApp.getFolderById('XXXXX')
var copy = file.makeCopy(companyName + '_one pager', folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText('{{Company Name}}', companyName);
body.replaceText('{{Name}}', name1);
body.replaceText('{{Position}}', position1);
body.replaceText('{{Email}}', emailAdd1);
body.replaceText('{{Linkedin}}', linkedin1);
body.replaceText('{{Fun Fact}}', funFact1);
body.replaceText('{{Game Stage}}', gameStage);
body.replaceText('{{Game Story}}', gameStory);
doc.saveAndClose();
folder.createFile(doc.getAs("application/pdf"));}
My template -
Result -
Question - Does that mean the array declaration in line 3 was supposed to match the order of my form responses columns?
You can use Regular Expresion:
body.replace(/{{Company Name}}/g, companyName); // /g replace globaly all value like {{Company Name}}
Finally I found what have went wrong after so many trials and errors!
The reason is because I declared the array variables randomly without following the order of the form responses columns.
The issue is with the part -
var [companyName, country, totalEmployees,totalPctWomenEmployees,numberNationality,name1,position1,emailAdd1,linkedin1,funFact1,name2,position2,emailAdd2,linkedin2,gameStage,gameStory] = response.getItemResponses().map(function(f) {return f.getResponse()});
It's actually pulling responses from the spreadsheet, and should be corrected in order. The wrongly mapped values was what causing the replacement of text went haywire. I corrected the order as per form responses and it is all good now.
Learning points:
If you swapped around the variables, what response.getItemResponses().map(function(f) {return f.getResponse()} does is that it will go through the form responses column by column in order, and it will map the content to the wrong variable. As a result, when you replace your text later using body.replaceText('{{Game Stage}}', gameStage), there might be possibility that whatever stored in gameStage might be name1. Hence the replaced text will be wrong. And you will scratch your head until it bleeds without knowing why.
I saw #Tanaike's comment after I found the answer, but totally spot on!
This is definitely a pretty basic question, but I can't seem to find a solution by myself, nor the answer in the depths of the internet.
Java script skill: Newbie
I am getting Google Forms Item Id's so that I could then edit/delete etc. even after somebody edits outside of my script.
To get them Ids I am using a 'for loop', which comfortably gets them for me in a string. Unfortunately I don't know how to save that result in a variable - always getting a syntax error.
I am also not happy with saving the logger.log in my google sheet.
Any ideas?
This is my code:
function GetItems3(){
var formId = "your-id";
var Form = FormApp.openById(formId);
var ajtems = Form.getItems();
for(var i=0;i<items.length;i++)
{ajtems[i].getId().toString()
Logger.log(ajtems[i].getId().toString())
};
//That saves the logger log in my sheet (DMsheet is a global var)
var A = DMsheet.getRange(15, 6, ajtems.length, 1).setValue(A);}
Thanks in advanc3
There are several things wrong from your code.
1) There is no need to use the .toString() method because getId() already returns the id as a String.
2) You didn't define your ajtems var.
3) You can't declare a var like A and use it at the same line you are declaring it because it hasn't been set yet.
4) You didn't declare DMsheet, this variable should contain your sheet and you would get it using the Class Sheet.
5) You said in your post "Java skill: Newbie". Java and JavaScript are not the same.
This code will help you to solve your issue:
function GetItems3(){
var formId = "your-id";
var Form = FormApp.openById(formId);
var items = Form.getItems();
// Get a sheet from the Spreadsheet you are running your script
var dmSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
// Create an empty array to save the Form's items
var myArray = [];
for(var i=0;i<items.length;i++){
Logger.log(items[i].getId());
// Sotre the title items in the array
myArray.push(items[i].getTitle());
};
// Set the values in your sheet
dmSheet.getRange(1, 1, 1, items.length).setValues([myArray]);
}
I really recommend you to take your time to read the Apps Script docs. It will help you a lot to improve your coding and clear your doubts on how to use Apps Script in the best way possible.
I have written a very simple code on my Google Sheets file. This is the purpose:
Save some cells values from StaticSheet (all the Copyxxx) that need to be copied in DynamicSheet.
Get the value of one specific cell inserted by the user manually.
Enter a While loop useful only to increase an indicator and get the number of the row where I want to copy those values previously saved.
Copy those values on this row but different columns.
The problem is that it seems that most of the time it does not even run the script after I told it to do so.
What is funny is that sometimes it works, super slowly, but it works for like a couple of minutes. And after it stops working again.
Could you please tell me what am I missing here please?
function Copy_Static_on_Dynamic() {
var app = SpreadsheetApp;
var ss = app.openById("xxxxyy--------yyzzzz")
var StaticSheet = ss.getSheetByName("DEAT Price");
var DynamicSheet = ss.getSheetByName("DEAT Price + TEST");
var CopySKU = StaticSheet.getRange(5,1,40);
var CopyPrices = StaticSheet.getRange(5,3,40,4);
var CopyUsage = StaticSheet.getRange(5,8,40);
var Week_1 = StaticSheet.getRange(2,4).getValues();
var i = 1;
Logger.clear();
while(DynamicSheet.getRange(i,3).getValues() != Week_1)
{
Logger.log(i);
i+=1;
}
CopySKU.copyTo(DynamicSheet.getRange(i,4,40));
CopyPrices.copyTo(DynamicSheet.getRange(i,6,40,4));
CopyUsage.copyTo(DynamicSheet.getRange(i,11,40));
}
If you see the "Preparing for Execution" message in the Apps Script editor, you can reload the browser window and run the function again. The program will likely go away.
So I think I have solved it.
As Serge insas was saying I had my script running on the background, I found it out on the "Execution" section, where you can also interrupt them.
After I discover it I kept testing, and I saw that the while loop needed almost 2 seconds to check the condition every time, making the script incredibly long.
So instead of:
while(DynamicSheet.getRange(i,3).getValues() != Week_1)
... I have created a variable declared previously such as:
var WeekLOOP = DynamicSheet.getRange(i,3).getValues();
while(WeekLOOP != Week_1) { --- }
... and now the script needs few milliseconds to run the condition. I don't have enough technical knowledge to say if this was the only issue, but is what apparently solved my problem.
Thanks to all for the support! Will come back if I need any further help :)
As was mentioned by Amit Agarwal, to solve the error message mentioned on the question, refresh the web browser tab.
Regarding the code,
On
var Week_1 = StaticSheet.getRange(2,4).getValues();
and
DynamicSheet.getRange(i,3).getValues()
instead of getValues you should use getValue because your code are referring to single cell cells otherwise you will be getting 2D arrays instead of scalar values.
The use of while should be made very carefully to avoid functions running endlessly. You could add some "safeguard" like the following
var max_iterations = 100 // Edit this
while(DynamicSheet.getRange(i,3).getValue() != Week_1 && i <= max_iterations) {
I have a page where my team could enter data into one page and then hit a save button, then it would copy and paste the data into a database file then clear the contents of the original page.
What I'm trying to figure out is how I can hard stop the save if the pasted information is incorrect.
example. they copied the incorrect information from the one program we use and paste it into the spreadsheet. but the customer number is in the wrong cell.
This would skew the information in the database.
So my thoughts were to have a criteria check of some sort. So it would check the data in a specific column of cells and check to see if it were between 10000 and 99999 or check to ensure it has 5 digits. then have a second check for something similar.
It would be better if I can find a way to have a Paste button that could paste the information and have the hard stop within that code. But baby steps...
function Copy() {
var sss = SpreadsheetApp.openById('file name here');
var ss = sss.getSheetByName('InputData');
var range2 = sss.getRange('D8:O1000');
var range = ss.getRange('A8:Q1000');
var data = range.getValues();
var tss = SpreadsheetApp.openById('file name here');
var ts = tss.getSheetByName('OutOfStockData');
ts.getRange(ts.getLastRow()+1, 1, data.length, data[0].length).setValues(data);
range2.clearContent();
}
Any help would be greatly apricated.
Thanks.
EDIT.
I'm unable to use forms as we copy the information from an internal WMS program we use. When we copy the information, it gets copied in a format that is recognized by any spreadsheet. So we would just copy and paste into the spreadsheet and then add any extra information needed to each line in the extra columns. (ie. comment column.)
The checks needed is so I can get accurate information on Stockouts. Sometimes an error can be made when one of my teammates copies information from a different window in WMS. so one check like mentioned before would be customer number which is always in column J. and never more than 99999 or less then 10000. another check could be the Case ID which is always in column D which is never more then 9999999 and less then 1000000. verifying these two columns could prevent the data from being skewed if the wrong information is copied from WMS.
So the Information gets Copied from WMS, Pasted into InputData, then when the added information gets entered I would click the save button and it would take all the data in the inputData sheet and copy it into the outofstockdata sheet where It would be used for other metric data needed.
As far as the Paste button, Some of the guys who would need to use this sheet are not very computer literate. So the goal would be to have them press said Paste button and the information from our WMS program which would be on the clipboard within windows(no different than copying and pasting from an email to a word document). which we have copied earlier be pasted into the Frist sheet where we would comment.
Thanks.
To hard stop an script that met a condition use return. This could be shown with vanilla JavaScript
function myFunction(){
var upperLimit = 10;
var lowerLimit = 5;
var input = prompt('Give me a value');
// This is the condition that will hard stop the script.
var condition = input >= lowerLimit && input <= upperLimit;
if (condition){
return; // This hard stop the script.
} else {
//if the condition is not met, continue
myFunction();
}
}
myFunction();
I have tried searching and haven't been able to see anything that can parse in JavaScript.
It would only have to parse a .txt (tab delimited) file with the following:
L123____Donald____Duck____247.09
S234____Mickey____Mouse___356.09
F456____Daffy_____Duck____1650.36
N876____Minnie____Mouse___60.45
It would have to pull out the number, first initial of first name, first initial of second name and then the number at the end (concentration). The first 3 L123, D and D could all be given a var, but the concentration number would have to get a separate one as I have to do some funky calculations and the assign it function in a liquid handling robot.
Any help on this gratefully received, even if it's only partial as I like to try and work things out ( sometimes ;-) )
I use this to test things at the moment because I don't know what else to use: https://www.w3schools.com/js/
Thank you
var input = /* your data */;
var table = input.split("\n").map(line => line.split("\t")); // here's your table