I'm trying to create a macro to have a box prompt to confirm the action like "Do you want to clear the sheet?" with a yes or no question.
If YES, to delete the given cells
If NO, do nothing.
The YES condition works. But I can't seem to make the NO work. Even if I click on NO, it still executes the clear command. What am I doing wrong?
I'm not well versed in coding. I simply rely in Google. I have tried to change the "else" to "End if" and also tried "then" but none works. I'm not sure how to stop the code from running.
function myFunction() {
var sh1=SpreadsheetApp.getActive();
var sheet1=sh1.getSheetByName("Sheet1")
var sh=SpreadsheetApp.getUi();
var response=sh.alert("Clear?",sh.ButtonSet.YES_NO)
if(response.YES);{
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
sheet.getRange('b1:b21').clearContent();
sheet.getRange('C13:C18').clearContent();
}
Else {}
}
Even clicking NO from the prompt it still executes the clearContent command.
You're not using response correctly. It contains a UI.Button.YES or UI.Button.NO value. The correct test would be
function myFunction() {
var sh1 = SpreadsheetApp.getActive();
var sheet1 = sh1.getSheetByName("Sheet1")
var sh = SpreadsheetApp.getUi();
var response = sh.alert("Clear?", sh.ButtonSet.YES_NO)
if(response == UI.Button.YES) {
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
sheet.getRange('b1:b21').clearContent();
sheet.getRange('C13:C18').clearContent();
}
}
For more information, see the documentation for UI.Alert
(You also had a misplaced ; in your original code after the if(), with if(response.YES);{, which my answer removes as well.)
Related
https://docs.google.com/spreadsheets/d/1rGns0DGQbjlEpxTbdy1T_-m2oh7eK8tM9xyDzGqahJo/edit?usp=sharing
So I have this code that I thankfully got of the internet but I can't seem to get it to copy the other values in column 'C' from a code I have that fills in empty cells, sheet provided for reference.
function ss1OnEdit(e){
if(e.range.getSheet().getName()!='source_sheet') return;
SpreadsheetApp.openById("1rGns0DGQbjlEpxTbdy1T_-m2oh7eK8tM9xyDzGqahJo").getSheetByName("target_sheet").getRange(e.range.getA1Notation()).setValue(e.value);
}
//You can run this function all you want it will not create more than one trigger. But you must run it once to setup the first trigger.
function createSS1OnEditTrigger() {
var ss=SpreadsheetApp.getActive();
var trgs=ScriptApp.getProjectTriggers();
var found=false;
for(var i=0;i<trgs.length;i++) {
if(trgs[i].getHandlerFunction()=="ss1OnEdit") {
return;
}
}
if(!found) {
ScriptApp.newTrigger("ss1OnEdit").forSpreadsheet(ss.getId()).onEdit().create();
}
}
This code only sets the values that have been entered manually by hand. I would really appreciate if we can have it set cell value from code input.
I have been reading about this for a bit and the getdisplayvalue() but nothing so far worked for me.
Thank you!
I assume that your question is why the user input fires the trigger, but the Range.setValues() doesn't. If that is correct, then it works as written on the simple trigger docs: «onEdit(e) runs when a user changes a value in a spreadsheet». So a user change will fire the trigger, but a script change won't.
Basically I am receiving errors about the formsubmit and everything has been changed around multiple times and re-edited PLUS re written but the script just wont budge.
I have deleted and recreated+edited the code multiple times and deleted and recreated the trigger multiple times and to no avail.
I originally made it so only hard edits could work to bring data down to the bottom cells but that is not what I wanted in the end.
/** #OnlyCurrentDoc */
function formsubmit()
{
var sheet=SpreadsheetApp.getActiveSheet();
var email_address = Session.getActiveUser().getEmail();
var lastRow=sheet.getLastRow()
var lastColumn=sheet.getLastColumn()
var entries=sheet.getRange(lastRow,1,1,lastColumn)
for(var i=1; i<=lastColumn; i++)
{
var cell=sheet.getRange(lastRow,i).getValues()
if(cell==0)
{
var previousCell=sheet.getRange((lastRow-1),i).getValues()
sheet.getRange(lastRow,i).setValues(previousCell)
}
}
}
6/23/19 4:48 PM
myFunction
Script function not found: myFunction
formSubmit
6/23/19 4:48 PM.
Edit: I believe it is case sensitive.
So Google Sheet is looking for 'formSubmit', when your function is called 'formsubmit' (lower case S)
I have a date input in my page, which I'm using Daterangepicker framework to populate it.
Here is the code of how I start my page!
$(function(){
startSelectors();
var variaveis = returnInputVars();
var rede = variaveis[0];
var codLoja = variaveis[1];
var period = variaveis[2];
console.log('1.'+rede+' 2.'+codLoja+' 3.'+period);
});
function returnInputVars(){
var rede = $("#dropdown-parceria").val();
var codLoja = $("#dropdown-loja").val();
var periodo = $("#datepicker-range").val();
return [rede, codLoja, periodo];
};
The function startSelectors() is set to start my datepicker and other fields, which is working perfectly. After it, I create a var called "variaveis" to fill
with the values of each field because I will use then later (this functions also works perfectly at other scripts of my page).
Running the page, my console returns this:
The funny thing is, if I type at the console this, the value is shown, just while starting the script is does not work!
Anybody experienced something like this?
***UPDATE
Adding this script to my start function:
console.log($("#datepicker-range"));
The value is shown, but the second console.log don't:
EDIT 1. FIDDLE (Suggested by #halleron)
To ensure things are loaded in the correct order, it is useful to apply a page sniffer code snippet that will scan the page continuously until a condition is met, or until a preset counter limit is reached (to prevent strain on browser memory). Below is an example of what I typically use that would fit your scenario.
I think because you are dealing with asynchronous loading, you can't have a global variable that holds the values in a global scope without an interval to detect when it can be used. Otherwise, it will attempt to read the variable when it is not yet ready.
You can invoke functions anywhere you like. But I would keep all of your variables contained within the page_sniffer_2017() because that is a controlled environment where you know that everything successfully loaded and you know that the variables are ready to be accessed without error.
That way, regardless of connection speed, your functions will only fire when ready and your code will flow, sequentially, in the right order.
Within the ajax success options, always add a class to the body of the document that you can search on to determine if it has finished loading.
$(document).ready(function() {
page_sniffer_2017();
});
function page_sniffer_2017() {
var counter = 0;
var imgScanner = setInterval(function() {
if ($("#datepicker-range").length > 0 && $("#datepicker-range").val().length && jQuery('body').hasClass('date-picker-successfully-generated')) {
var periodoDatepicker = $("#datepicker-range").val(); // ok
console.log(periodoDatepicker); // ok
var variaveis = returnInputVars(replaceDate(periodoDatepicker)); // ok
console.log(variaveis[0], variaveis[1], variaveis[2]);
//startNewSelectors(variaveis);
// start ajax call
generateData(variaveis[0], variaveis[1], variaveis[2]);
clearInterval(imgScanner);
} else {
//var doNothing = "";
counter++;
if (counter === 100) {
console.log(counter);
clearInterval(imgScanner);
}
}
}, 50);
}
I have a javascript function which is called by a 'onsubmit' within a form (Coldfusion).
<form action = "person2aa.cfm"
name = "pers2form"
method = "post"
style = "margin-left: 125px"
onsubmit = "return test()">
When the function test() is located directly below this form statement it works correctly:
<script>
function test(){
alert("got to test");
var yesa = document.getElementById('yesnoa').value;
var yesb = document.getElementById('yesnob').value;
var xx = document.getElementById('ln').value;
var x = xx.trim();
alert('supbpers2 x is ' + x);
if (x < "!"){
document.getElementById('writeval').innerHTML = "You must enter a last name.";
return false;}
else
return true;
}
</script>
(The remainder of the form continues below this script).
When I place this function anywhere else, it does not run. I have tried it in the header of the html page, and also on another page, person.js, to which the link is:
<script type = "text/javascript" src = "person.js"> </script>
The first alert 'got to test' runs in these places, but the first line starting var yesa = does not execute and the function therefore does not execute either.
The id's 'yesnoa', 'yesnob', 'ln' and 'writeval' are in the code and are correct (or the inline script would not run, but I checked anyway).
I previously had this script (minus the alerts) in the header section of my program, and it was working at one point. I have returned to retest the program some months later and the script was not functioning. I have not made any changes to this script at any time. The program itself was altered by the addition of 4 trivial queries to do various things but all look something like this:
<cfquery name = 'aa11' datasource = "Moxart">
update NameInfoDb
set perloc = <cfqueryparam value = "#perloc#">
</cfquery>
I cannot think of any connection between these additional queries and the failure of the javascript.
Can anyone explain what the problem might be? There must be an explanation, and I need to know it so I will not repeat whatever the bad code is.
I'm a beginner at this, so this error might be on account of faulty coding, but this is why I'm here! lol.
I have written a Sheets function that (in theory) would go through all the files in a particular folder and find all the instances of a particular word and then return the number of instances of that word. Here is the code I wrote:
function commentCount(name) {
var files = DocsList.getFolderById('FOLDER ID GOES HERE').getFiles();
var counter = 0;
for(i in files) {
var doc = DocumentApp.openById(files[i].getId());
var text = doc.getText();
text = text.replace( /\./g, "" );
var textArray = text.split(" ");
for(w in textArray){
if(textArray[w] == name){
counter++;
}
}
}
return counter;
}
When I call the function in Sheets, an error reads - Error: You do not have permission to call getFolderById (line 3, file "commentCount")
I've tried using getFolder("Folder name"), and getFolder(path), and the same error occurs. It seems that the DocList functions are not working correctly.
Not sure what the issue is because everything seems fine when I debug the function.
I won't be able to figure out if the rest of my code is sound until I figure out this error. Any help would be greatly appreciated!
Phil Bozak clarified that formulas in Spreadsheets that call scripts functions do not get full permissions, which makes it impossible to use getFolderByID function in this case.