I'm trying to make a Google Sheet that opens to an assigned sheet automatically for a large team using their gmail addresses when accessing it. How do I slice a string in Apps Scripts? The "email.slice" on line three is just something I made up as a place holder.
function onOpen() {
var email = Session.getActiveUser().getEmail();
var username = email.slice[0:-9];
var ss= SpreadsheetApp.openById(username);
SpreadsheetApp.setActiveSpreadsheet(ss);
}
The slice method returns part of the string. You could return all of it, but there's no point in that. There are two parameters, one is optional, the start and end parameters. Start comes first, end is second, and end is optional. If the end parameter is not used, the method automatically goes to the end of the string.
Apps Script uses JavaScript, so any JavaScript reference material that you want to use will give you the answers for almost everything related to basic programming.
In your case, you need to combine slice with indexOf().
var username = email.slice(0, email.indexOf("#"));
Logger.log('username is: ' + username); //VIEW, LOGS to see print out
Substring will work as well
var username = email.substring(0, email.indexOf("#"));
Here is what I ended up doing:
function onOpen() {
var email = Session.getActiveUser().getEmail();
var ldap = email.slice(0,-11);
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName(ldap));
}
Worked well.
Related
I am trying to get Google sheets to send personalized emails from long list on another sheet in the workbook. I used a tutorial (as I am a certified novice at all coding languages) but the AppScript is telling me that line 4 has a syntax error. I cannot for the life of me figure out what I've done wrong, but I'm sure that its blatantly obvious when explained by someone with these legitimate skills. Here is the script:
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet1=ss.getSheetByName(‘Sheet1’);
var sheet2=ss.getSheetByName(‘Sheet2’);
var subject = sheet2.getRange(2,1).getValue();
var n=sheet1.getLastRow();
for (var i = 2; i < n+1 ; i++ ) {
var emailAddress = sheet1.getRange(i,2).getValue();
var name=sheet1.getRange(i,1).getValue();
var message = sheet2.getRange(2,2).getValue();
message=message.replace(“<name>”,name);
MailApp.sendEmail(emailAddress, subject, message);
}
}
Anyone that could help me get this running would be a true life saver!
The code in the question has ‘, ’ and “,” (opening/closing curly single and double quotes) instead of ' and " (straight single and double quote). Replace the first by the corresponding straight quote.
I have seen that this problem usually happens to people new to Google Apps Script that find a "nice" piece of code on a website that isn't really friendly for publishing code. It's very likely the website is using something that replaces straight quotes by the also called typographic quotes.
Related
Notify via email when a cell is updated in google spreadsheet
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Illegal_character
Try to change the following code, might be you are using the wrong apostrophe and you forget to put ; in second line
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName('Sheet1');
var sheet2 = ss.getSheetByName('Sheet2');
function sendEmail() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sheet1=ss.getSheetByName('Sheet1');
var sheet1sr=2;//data start row
var sheet2=ss.getSheetByName('Sheet2');
var subject=sheet2.getRange(2,1).getValue();
var msg=sheet2.getRange(2,2).getValue();
var vA=sheet1.getRange(sheet1sr,1,sheet1.getLastRow()-sheet1sr+1,2).getValues();
for (var i=0;i<vA.length;i++) {
let message=msg;
message=message.replace("<name>",vA[i][1]);
if(MailApp.getRemainingDailyQuota()>0) {
MailApp.sendEmail(vA[i][0], subject, message);
}else{
SpreadsheetApp.getUi().alert('Remaining Daily Quota is exhausted.')
}
}
}
You were using incorrect single and double quotes also
I am trying to build a Gmail database for all users in our company, I want to get these Gmails through piece of code and apply an if condition on them to see if they match or not, but I am not successful so far. I don't know if it's because the string I retrieve can't be read as an apps script syntax or it's because I am doing it wrong. here is my code:
I put all needed Gmails in 1 cell (B3) like this --->
(user == 'abc1#gmail.com') || (user == 'abc2#gmail.com')
//my code
var user = Session.getEffectiveUser();
var mailDB = SpreadsheetApp.openById('Sheet ID').getSheetByName('Sheet Name'); //mails database
var cellcondition = HeadOfficeMailDB.getRange("A3"); // cell with certain value 22
var Gmails = mailDB.getRange("B3").getValue(); //retrieve Gmails in the cell as one whole string
if((Gmails) && (cellcondition == 22))
{
var newcell = HeadOfficeMailDB.getRange("C3").setValue(4);
}
I set the Database with 2 different Gmails, but when I run the code with a third Gmail not included in Database, it runs anyway. it seems like it doesn't recognize the string as a syntax, or am I doing something wrong?
kindly if you have any fix or recommendations or other better ideas to handle such issue please don't hesitate to provide me with your assistance immediately.
The following line
var cellcondition = HeadOfficeMailDB.getRange("A3");
assigns a Class Range objec to cellcondition. Replace it by
var cellcondition = HeadOfficeMailDB.getRange("A3").getValue();
to assign the value of A3 to cellcondition.
To evaluate the value of Sheet Name!B3 ((user == 'abc1#gmail.com') || (user == 'abc2#gmail.com')) you could use eval() but doing this is an enormous security risk. It's better to store the email address as a list (separated by using a separator like a comma) then use String.prototype.split() and Array.prototype.index() or create a Set object.
Related
javascript pass eval variables
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 am working on a project where I take multiple column/row inventory sheets and turn them into a multi-row/2-column format for order picking.
I have a switch for selecting the appropriate inventory sheet and a map() function that copies the imported information from the inventory DataRange().
However, not all the data is in consistent columns. What I would like to do is find an expression that maps the next column in if the column it was mapping has a zero or "" value.
I won't give you the full body of code unless you need it, but hopefully just the important parts.
This is what I have:
var source = SpreadsheetApp.openById("1xixIOWw2yGd1aX_2HeguZnt8G_UfiFOfG-W6Fk8OSTs"); //This sheet
var srcSht = SpreadsheetApp.getActive();
var sourceMenu = srcSht.getRange('A1');//This is the cell cotaining the dropdown
var menuTest = sourceMenu.getValue();
// Variable for the vars sheet. If it doesn't exist, create it
var varsTest = source.getSheetByName('vars');
if (!varsTest){source.insertSheet('vars');}
var importedA1 = varsTest.getDataRange().getA1Notation();
varsTest.clearContents();
var t1Imp = '=ImportRange("test1_Id", "Stock!A1:F11")';
var varsData = varsTest.getRange('A1');// This is the cell we fill with the importRange formula
varsData.setValue(t1Imp);
var imported = varsTest.getDataRange().getValues();
var newOrder = imported.map(function(item) {
if (item[4] !== NaN){return [[item[0]],[item[4]]];};
if (item[4] === NaN){return [[item[0]],[item[3]]];};}
var orderRange = source.getSheetByName('Sheet1').getRange(10,1,newOrder.length, newOrder[0].length);
orderRange.setValues(newOrder);
Logger.log("\t" + newOrder);
Logger.log(newOrder):
[(timestamp omitted)] items1,order,caramel,6,c&c,2,mint,3,PB,0,,,items2,,caramel,,strawberry,,mint,,PB,
It seems to be skipping the if statements, or I told it that I mean to test the index as NaN, which will obviously never be true.
I also tried replacing 'NaN' with 'undefined'. Same result. I tried finding the item[4].Values, but it gave me an error. I also tried the same logic using filter() instead of map() but it copied the entire data set.
I pull these values onto a new 'vars' sheet in the workbook (to minimize calls to the web service):
test1
reduce them to the first and last columns, then output:
test
The cells in the 'order' column for the second set of items in the 'test' sheet are blank. The values for that order column should be in item[3] of that array, but I can't get the script to identify that that the blank cells are blank.
I am new to Google Apps Script and JS, but I am watching a lot of tuts and learning by doing. If I find a solution, I will post it.
Thank you StackOverflow, I could not have learned as much as I have without this community!
I have a working function that does what I want. In short:
I had to create a duplicate of the order column in a new column, so that all the values would line up. It's not technically a JS answer, but was the simplest and follows good spreadsheet rules.
function rmZeroOrderPS(item){
var source = SpreadsheetApp.openById("<sheetId>"); //This sheet
var varsTest = source.getSheetByName('vars');
var imported = varsTest.getDataRange().getValues();
var i=-1;
while (i <= imported.length){
if(item[8]!= 0) {return [item[0],item[8]]};
i+=1;
};
I have an "Invalid character error" while using JS script to extract mails from text that I cannot handle for last 2 days.
I am getting text from web application by using Object cloning and passing it to variable which i will later pass to JS script.
And of course my JS script which I checked and it works:
var args = WScript.Arguments;
var pattern = \w+#\w+.\w;
var result = /pattern/.exec(args);
WScript.StdOut.WriteLine(result);
First and foremost lets break this down it modules and debug them.
.
First Module: Object cloning
Object Cloning is very good to build reliability and this reliability is acheived by careful selection of Properties and in your example you have selected Path,DOMXPath, HTML Tag
Its a good practice to identify the properties which are unique and therefore yield high accuracy and some of these properties depend on the context
For example in a login page some properties include:
Priority 1: Path, HTML ID, InnerText
Priority 2: DOMXPath, HTMLValue
You may chose to add properties that you think may be unique to your context
Does strResult give you the expected value ? If yes, lets proceed
Second Module: Run Script
Accepts 2 Parameters $strResult$ and $mail$
And of course my JS script which I checked and it works:
and you have confirmed the JS module also runs fine
If you have verified the results of the first 2 modules, I think there could be an Invalid character somewhere in the script, parameters, check the regular expressions used. Shouldn't the pattern be enclosed in string " " ??
=====================
EDIT:
I wanted to recreate the issue and give you the desired result but I do not know your intended input and output for Javascript. However to the best of my understanding of your javascript, I have compiled and executed this script in Automation Anywhere and works perfect.
JavaScript
var args = WScript.Arguments;
if (args.length > 0)
{
var val=0;
var str=args.item(0);
var ary = str.split(",");
//WScript.Echo(ary.length);
// for loop in case there are multiple parameters passed
for (var i=0; i < ary.length; i++)
{
//Takes the input passed as parameter
var input = (ary[i]);
// Uses the Match() Method to look for an email address in input string
var result = input.match(/\w+#\w+\.com/);
//returns the email address
}
WScript.StdOut.WriteLine(result);
}
OR
//Takes the input passed as parameter
var input = (ary[i]);
//Declares the pattern used
var pattern = /\w+#\w+\.com/
// Uses the Exec() Method to look for a match
var result = pattern.exec(input);
//returns the email address
Run Script
Input Parameter
Output Parameter