Google Apps Script : reference error getValue is not defined - google-apps-script

I'm working on a Google App Script to use it in a spreadsheet:
I just want to get the value in the ID tab, cell B2
function onInstall(e) {
onOpen(e);
}
function onOpen(e) {
var menu = SpreadsheetApp.getUi().createAddonMenu();
menu.addItem('Générer RM', 'createRM');
menu.addToUi();
}
var responsableProjet = {};
function createRM() {
getAdminInfo();
}
function getAdminInfo() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
responsableProjet.sexe = getValue(sheet, 'ID!B2');
}
I'm having this weird error..
Thanks for your help ! :)

You have to define a range then, you can call "getValue" : https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangea1notation + https://developers.google.com/apps-script/reference/spreadsheet/range#getvalue
The code could be something like :
responsableProjet.sexe = sheet.getRange('ID!B2').getValue();
to test...

Related

GoogleJsonResponseException: API call with error: Login Required

I made a script using the advanced service API Google Drive. It's working fine when we stay into the app script GUI :
/** #OnlyCurrentDoc */
function GetListOfDrivesName() {
const ALL_AVALIBLE_DRIVE = Drive.Drives.list();
return ALL_AVALIBLE_DRIVE.items.map(driveData => driveData = driveData.name)
}
However, when it's called from cell into Google Sheet we got an error
Error message is like below : GoogleJsonResponseException: API call to drive.drives.list failed with error: Login Required.
I guess it's some authentification & authorisation to ask before using the sheet.
Unfortuantly I have no idea how to request that ! I read doc but it's sound like it will be asked promptly.
In addition, trigger have been added for this function but it neither worked
Any idea ? Thanks in advance !
Hi #Yuri Khristich you were right, using ui is a good work around , code turn up to work corectly
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var ui = SpreadsheetApp.getUi();
ui.createMenu('[FM Script for G Drive]')
.addItem('test','showAvaillableDrive')
.addToUi();
}
function showAvaillableDrive(){
var ui = SpreadsheetApp.getUi();
var resultat = ui.prompt(GetListOfDrivesName())
}
function GetListOfDrivesName() {
const ALL_AVALIBLE_DRIVE = Drive.Drives.list();
return ALL_AVALIBLE_DRIVE.items.map(driveData => driveData = driveData.name)
}
As suggested by the comments you can build a menu over the Sheet and run it to write down Drive files that I own.
I have this custom Sheet where you can run the "Drive" function over "Adv Menu"
I automatically get the information of the Sheet and get a list of my Drive files:
function onOpen () {
var ui= SpreadsheetApp.getUi();
ui.createMenu('Adv Menu').addItem('Drive', 'getMyFilesFromDrive').addToUi();
}
function getMyFilesFromDrive() {
var myFiles = DriveApp.searchFiles('"me" in owners');
var sheet = SpreadsheetApp.getActive().getSheetByName("Files");
sheet.clear();
var rows = [];
rows.push(["ID", "Name", "Url"]);
while(myFiles.hasNext()) {
var file = myFiles.next();
if(file != null) {
rows.push([file.getId(), file.getName(), file.getUrl()]);
}
}
sheet.getRange(1,1,rows.length,3).setValues(rows);
}
It would also write it directly to my Sheet. Feel free to review it and use it.
You can also Draw a button (Inserting a Google Drawing) over the Sheet and assign a script:
Reference:
https://developers.google.com/apps-script/guides/menus

Assign any kind of protection to a custom menu

If it is not possible , can i make any trick to open a msgbox then end the script if anyone try to access the script
Here is my code :
function onOpen(){
var ui = SpreadsheetApp.getUi();
var menu = ui.createMenu('Private');
menu.addItem('Clear Cols','clearAli');
menu.addItem('Enter Number of days','noOfDays');
menu.addItem('subject','myEmail')
menu.addToUi();
} 
function clearAli(){
var ss = SpreadsheetApp.getActive();
ss.getRangeList(['G2:K108', 'M2:M108', 'O2:O108']).activate().clearContent();
}
function noOfDays(){
var
days =  SpreadsheetApp.getUi().prompt('Please enter the number of days.').getResponseText();
SpreadsheetApp.getActiveSpreadsheet().getRange('H2:H5').setValue(days);
}
function myEmail(){
const
subject = SpreadsheetApp.getUi().prompt('Enter your subject line').getResponseText();GmailApp.sendEmail('noelaramouny#gmail.com,alinemanoukian04#gmail.com',subject,'https://docs.google.com/spreadsheets/d/1Z92UC7RAqScObY2vpAKlzIvoY4yihxRtqw_2LEB2-8g/edit?usp=sharing');
}
const whitelist = ['mail1', 'mail2'];
const user = Session.getActiveUser().getEmail();
if (!whitelist.includes(user)) {
Browser.msgBox('Not in whitelist');
return;
}

How can i create a button in a cell using only google app script? not with the Insert>drawing option

I need to do a button with a script its required for the thing i want to do so the button that can be created in insert>draw option doesn't have what i need, i want to put a entire call with buttons in each row son any button execute a function when is clicked, I want to know if this is possible
I looked about this information here, but really dont know how to do it
Using one script for copying text from cells in a row to another sheet using an icon in a row
Script in my html that embed my trello cards
<script>
(() => {
google.script.run.withSuccessHandler(myname => {
const tag = document.createElement('script');
tag.src = "https://p.trellocdn.com/embed.min.js";
tag.addEventListener('load', () => {
const elem = document.querySelector('#card');
elem.href = myname;
window.TrelloCards.load(document); // <-- this triggers the lookup
});
document.body.append(tag);
}).getCardById();
})();
</script>
Function getCardById
function getCardById(){
var app = SpreadsheetApp;
var activeSp = app.getActiveSpreadsheet();
var activeSheet = activeSp.getActiveSheet();
//Range of links
var linkRange = activeSheet.getRange(2,2,3,1);
//Cuantity of values
var filLength = linkRange.getValues();
var cont = 2;
if (activeSheet.getActiveCell().getColumn() == 6.0){
for (i = 0; i < filLength.length ; i++){
if (activeSheet.getActiveCell().getRow() == activeSheet.getRange(cont,2).getRow()){
var linkCol = 2.0;
var linkFil = activeSheet.getActiveCell().getRow();
var linkRange = activeSheet.getRange(linkFil, linkCol);
var linkValue = linkRange.getValue();
var url = linkValue;
return url;
}
cont++;
}
}
}
Function seeCard its the one that should be displayed when pressing the checkbox, when you press it should show you values of the same row
function seeCard(){
var app = SpreadsheetApp;
var activeSp = app.getActiveSpreadsheet();
var activeSheet = activeSp.getActiveSheet();
var startCol = 6;
var startFil = 2;
var numCols = 1;
var numFils = 2;
//Rango de links
var linkRange = activeSheet.getRange(2,2,3,1);
//Cantidad de valores para el for
var filLength = linkRange.getValues();
var cont = 2;
if (activeSheet.getActiveCell().getColumn() == 6.0){
for (i = 0; i < filLength.length ; i++){
if (activeSheet.getActiveCell().getRow() == activeSheet.getRange(cont,2).getRow()){
//Html
var templateFileId = '1upA3JHioEyxLScebasmsmwXW-SxsiKaPRznKLCKFYhw';
var sheetName = 'Trello sheet';
SpreadsheetApp.openById(templateFileId).copy(sheetName);
var excel = SpreadsheetApp.create("Probando un html interno a ver ")
var html = HtmlService.createHtmlOutputFromFile('index') //index is the name of your HTML file
.setTitle('Trello card')
.setWidth(350)
.setHeight(250);
SpreadsheetApp.getUi().showModalDialog(html, 'trello card '); // Or DocumentApp or FormApp.
//End
}
cont++;
}
}
}
Where is the button that says seeCard i need to put the checkbox and when you click grab the link send it to my html and show the trello card attached to that link
You want to put the checkboxes to the cells of "F2:F".
You want to run seeCard() when the checkbox is checked.
I could understand like above. If my understanding is correct, how about this answer?
Sample script:
Please copy and paste the following script. And, please install OnEdit event trigger to the function of installedOnEdit. Because in your script, when a simple trigger is used, an error occurs at the methods which are required to authorize like SpreadsheetApp.openById() and SpreadsheetApp.create(). So please use the installable OnEdit event trigger for this.
function installedOnEdit(e) {
const range = e.range;
if (range.columnStart == 6 && range.rowStart > 1 && range.isChecked()) {
range.uncheck();
seeCard();
}
}
In order to run the script, please check a checkbox at the column "F". By this, the function of installedOnEdit is run by the installable OnEdit event trigger. In your script, the active range is retrieved from your script. So in your case, I think that this sample script works.
Note:
I thought that the event object can be also used. But I'm not sure about your whole script. So I couldn't propose it.
References:
Installable Triggers
isChecked()
function onEdit(e) {
//e.source.toast('Entry');
const sh=e.range.getSheet();
if(sh.getName()=='Sheet13') {
if(e.range.columnStart==1 && e.range.rowStart==1 ) {
e.range.setValue('FALSE');
one(e);
}
if(e.range.columnStart==2 && e.range.rowStart==1 ) {
e.range.setValue('FALSE')
two(e);
}
}
}
function one(e) {
e.source.toast('This is function one');
}
function two(e) {
e.source.toast('This is function two');
}
Image:
Animation:

Google Sheets & Docs Script fails to create add-on menu when add-on is installed from Chrome store

Possible cause is the following:
Usually this is caused by a problem with the Authorization Lifecycle, specifically the opening stage.
The most common culprit is a global variable in the code that tries to access Google services without authorization, like:
var doc = DocumentApp.getActiveDocument();
See the documentation:
Warning: When your onOpen(e) function runs, the entire script is loaded and any global statements are executed. These statements execute under the same authorization mode as onOpen(e) and will fail if the mode prohibits them. This preventsonOpen(e) from running. If your published add-on fails to add its menu items, look in the browser's JavaScript console to see if an error was thrown, then examine your script to see whether the onOpen(e) function or global variables call services that aren't allowed in AuthMode.NONE.
Here is my script:
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Browse Templates', 'browseTemplates')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
function browseTemplates(){
collectBasicData();
// Display a modal dialog box with custom HtmlService content.
var htmlOutput = HtmlService
.createTemplateFromFile("Gallery").evaluate()
.setWidth(700)
.setHeight(510);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Spreadsheet123 - Template Vault');
}
function collectAllData(){
var sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(DATA_SHEET);
DATA = sheet.getDataRange().getValues();
return DATA;
}
function collectBasicData(){
var sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(PIVOT_SHEET);
var tabSheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(TAB_SHEET);
BASIC_DATA = {
"tab_about" : getValue(tabSheet,"B1"),
"tab_help": getValue(tabSheet,"B2"),
"pivot":sheet.getDataRange().getValues()
};
return false;
}
function getValue(sheet,addr){
return sheet.getRange(addr).getValue().toString().replace(/^\s+|\s+$/g, '');
}
function createACopy(id){
var docName = DocsList.getFileById(id).getName();
return DocsList.getFileById(id).makeCopy(docName).getUrl();
}
function insertInCurrent(id){
var destinationSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheets = SpreadsheetApp.openById(id).getSheets();
for(var i=0;i<sourceSheets.length;i++){
var sheetName = sourceSheets[i].getName();
var source = SpreadsheetApp.openById(id).getSheetByName(sheetName);
source.copyTo(destinationSpreadSheet).setName(sheetName);
}
}
Can you please help me a little or a lot.
Thanks in advance
OK, so my code was actually correct, but my mistake was that I should have saved any changes made to my code under the new version before publishing it to the store, which I did not and therefore all changes that I made were simply ignored.
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Browse Templates', 'browseTemplates')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}

Authorization Lifecycle on published add-on is not working

Have a problem with my add-on that should, but not creating a menu items in Add-ons on Google Sheets and Docs on install from the store until the page is refreshed.
According to Google Support I should look in to the following:
"Usually this is caused by a problem with the Authorization Lifecycle, specifically the opening stage.
The most common culprit is a global variable in the code that tries to access Google services without authorization, like:
var doc = DocumentApp.getActiveDocument();
See the documentation:
Warning: When your onOpen(e) function runs, the entire script is loaded and any global statements are executed. These statements execute under the same authorization mode as onOpen(e) and will fail if the mode prohibits them. This preventsonOpen(e) from running. If your published add-on fails to add its menu items, look in the browser's JavaScript console to see if an error was thrown, then examine your script to see whether the onOpen(e) function or global variables call services that aren't allowed in AuthMode.NONE."
I have no idea what and how should I deal with this as my add-on was not created by me. I can do minor things, but this is something that I cannot handle on my own and really need your help please.
Hear is my script:
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Browse Templates', 'browseTemplates')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
function browseTemplates(){
collectBasicData();
// Display a modal dialog box with custom HtmlService content.
var htmlOutput = HtmlService
.createTemplateFromFile("Gallery").evaluate()
.setWidth(700)
.setHeight(510);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Spreadsheet123 - Template Vault');
}
function collectAllData(){
var sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(DATA_SHEET);
DATA = sheet.getDataRange().getValues();
return DATA;
}
function collectBasicData(){
var sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(PIVOT_SHEET);
var tabSheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(TAB_SHEET);
BASIC_DATA = {
"tab_about" : getValue(tabSheet,"B1"),
"tab_help": getValue(tabSheet,"B2"),
"pivot":sheet.getDataRange().getValues()
};
return false;
}
function getValue(sheet,addr){
return sheet.getRange(addr).getValue().toString().replace(/^\s+|\s+$/g, '');
}
function createACopy(id){
var docName = DocsList.getFileById(id).getName();
return DocsList.getFileById(id).makeCopy(docName).getUrl();
}
function insertInCurrent(id){
var destinationSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheets = SpreadsheetApp.openById(id).getSheets();
for(var i=0;i<sourceSheets.length;i++){
var sheetName = sourceSheets[i].getName();
var source = SpreadsheetApp.openById(id).getSheetByName(sheetName);
source.copyTo(destinationSpreadSheet).setName(sheetName);
}
}
I have looked in to the documentation on Google, but cannot understand how and where I should use it in my script.
Your help is highly appreciated and thanks in advance