Passing in a Parameter in Google Spreadsheet Script from Script Assignment - google-apps-script

I'm trying to make my own button in a Google Spreadsheet, and I have a script called incrementContents that takes in a parameter (a cell location, eg 'B3') and increments that location by one.
My question is this- is there a way to pass in a parameter to this function via the same text box where I assign the script to the button (right click -> assign script)? Something like;
incrementContents('B3')
or
incrementContents, B3
I'm not sure of the syntax, and knowing how to do this would be very helpful.

You could do a couple of things -
Ask the user for the input using Browser.inputBox
Read cell's value from the script itself (if the cell reference is always constant) using an example like SpreadsheetApp.getActiveSheet().getRange("A1")

The way I am trying to work around this problem is by having the user edit a cell instead of adding a button to the cell. (Eg. typing "ok" in the cell.) This triggers the onEdit() function or a custom function that is passed the event parameter that can be used to get data from the sheet relative to the cell where the "ok" was entered.

Related

How to round a cell after user input in Google Sheets?

It should be a very simple function but I can't find anything that functions the way I need.
I want to have a cell where a number can be entered, then after its entered it is replaced by that number rounded to its nearest 0.25
For example:
I enter 5.26 into cell A1, after i press enter the cell now says 5.25
This should only happen with cell A1, so if i enter 5.26 elsewhere it will stay as 5.26
Any help? Thanks in advance and sorry if this a common question.
This can be achieve by using Google Apps Script and onEdit Trigger.
Follow these steps to achieve the desired goal.
In your Google Sheet, go to Tools -> Script editor.
Delete any code in the script editor and paste code provided below.
Click Save.
Go back to your Google Sheet and type numbers in cell A1.
Press enter and wait the value to change.
Code:
function onEdit(e) {
var range = e.range;
var input = e.value;
if(range.getA1Notation() == "A1" && !isNaN(input)){
var number = (Math.round(input * 4) / 4).toFixed(2);
range.setValue(number);
}
}
Demo:
Triggers let Apps Script run a function automatically when a certain
event, like opening a document, occurs. In your case, we need to use
onEdit since it runs automatically when a user changes the value of
any cell in a spreadsheet. Apps Script passes the
triggered function an event object that contains information about the
context in which the event occurred (usually named e).
In the demo above, I created a condition that will check if the edited cell is A1 and if the inputted value is number. If both satisfy the condition, the script will calculate the value and use range.setValue() to change the value of A1.
References:
Class Range
Range.setValue(value)
Simple Triggers
Event Object

Call custom function in google sheets only once and save value to cell

I have written a custom google apps script function that is being called by a google sheet. In this function an API is called and the result of this API is being returned so that it gets displayed in the calling cell of the google sheet.
My problem now is that the sheet calls this function everytime I open the document and there are over 80.000 cells with this function.
Is it possible to save the returned value to the cell and don't call the custom function again when an value has been returned? I want the function being called only once per cell, even if I close the document and reopen it. The returned value should be saved until something else is being written into to cell. That would make my sheets document much more usable than the current state.
From the question
Is it possible to save the returned value to the cell and don't call the custom function again when an value has been returned? I want the function being called only once per cell, even if I close the document and reopen it. The returned value should be saved until something else is being written into to cell. That would make my sheets document much more usable than the current state.
By solely using the custom function it's not possible. There isn't a straight forward solution is to achieve this, in order to keep things simple you should look for another way to implement what is being done by the custom funtion.
One option is to use a trigger (including a custom menu / a function assined to a drawing) to check if the cell that should have the value returned by the custom function is empty and in such case fill it with the corresponding value. The best trigger to use will depend on your spreadsheet workflow.
As specified by Ruben this is not possible, with a custom function.
In my particular case I have resorted to using an Apps Script function that is triggered by an edit event of the spreadsheet and verifies if the event is in the column where the function that I want to execute only once should be, later replacement its content with the result of calling the API.
function freezeValue(e) {
var rangeEvent = e.range;
var col = rangeEvent.getColumnIndex();
if (col === 2) { #Verify column of event
var value = rangeEvent.getValue();
/*Call your api*/
result_api = CALL_API(value)
rangeEvent.setValue(result_api);
}
}
Keep in mind that this implementation only works when each of the cells is edited one by one. To do the same with a row or a complete array of elements, you must go through each of the cells and follow the same procedure.

How to add date to empty cell by default if none specified in Google Form, on form submit with App Script?

I have a time log form that has a date field I do not want to have to fill out every time as 90% of the time the date would be today's date. (Sometimes you will be entering something from another day and need to change it).
When an entry is added column A is always going to have something, so it should check to see if A is empty and if that same rows D is empty it will input today's date into D.
Some of the example's I have looked at were for onEdit of cell change it, but I could not get it to work with a form submit or even just have it automatically check all the cells in D and if empty put today's date (Only when B has value).
I have a function to sort the sheet right now that is called when on form submit/onEdit happens and would like to stick the new formula in the bottom of the same one (unless that is bad practice). The reason for this is less functions to have to add to the trigger list.
A: Timestamp | B: What | C: Paid? | D: Date
You can try using Date from Google spreadsheets function list which Google Sheets offers.
And, as mentioned in Custom Functions in Google Sheets, if the available functions aren't enough for your needs, you can also use Google Apps Script to write custom functions then use them in Google Sheets just like a built-in function.
To get started, guidelines for custom functions and samples can be found in the given documentations.
You can use Google Apps Script with onFormSubmit trigger which will populate the said cell with default date.
Here is a sample code which will populate the current date in Column 4 of the row in question.
function onFormSubmit(e) {
//edit responses sheet name
var responseSheetName = 'Form Responses 2';
//Edit colmn number, column in which the date has to be autopopulated
var column = 4;
//Get target row number
var row = e.range.rowStart;
//If no date, pouplate the cell with current date
if(!e.values[column-1]){
SpreadsheetApp.getActive().getSheetByName(responseSheetName).getRange(row, column).setValue(new Date())
}
}
In order to setup the above code, open the Spreadsheet which contains the form responses. Go Tools > Script Editor. This will open script editor window. Paste above code and edit the responseSheetName and column . Now Save it.
After saving it, setup an on form submit trigger.
To setup the trigger, follow these steps.
From the script editor, choose Resources > Current project's triggers.
Click the link that says: No triggers set up. Click here to add one now.
Under Run, select the name of function onFormSubmit which you want to trigger.
Under Events, select From spreadsheet.
Select On form submit
Optionally, click Notifications to configure how and when you will be contacted by email if your triggered function fails.
Click Save.

Conditional formatting in Google Sheets: Can I use custom function in the 'custom formula is:' field?

While applying conditional formatting in Google spreadsheet, I was wondering if it's possible to use a custom function that I created via script editor in the field 'custom formula is:'. Here is what I did:
Went to 'script editor' and typed my fn as follows:
function foo (param1, param2, param3) {
if (condition to check) {
...some action;
return true;
} else {
return false;
}
}
and saved.
In sheet, selected cells and opened 'conditional formatting' dialog
Created new rule and in the field 'custom formula is:' typed the following
=foo(param1, param2, param3)
Unfortunately, this didn't work.
Addition
Here is the sample sheet...
See the two tasks in there. My aim is to have the 'task title' automatically written inside of the yellow field (see the task in row 6 where I entered the value manually).
What I already tried was:
- Assign to every cell in range H5:BB7 following formula: =if(H$4=D5; B5; "")
This checks if the start date equals the cell date and displays the task title.
That does the trick, however the content of the cell with task title is clipped even if 'overflow' is on because the next cell is not empty.
I have also found that custom functions cannot be used for conditional formatting. However, I located a pretty simple workaround.
The custom formula that I tried to use is:
=hasGreen(CELL("address",$H3)&":"&CELL("address",$M3))
ie. format a cell based on a range of other cells in that row.
My solution was to place the above formula into column P. Then I changed my conditional formatting's custom formula to =P3
Worked like a charm. Any change to H3:M3 would call hasGreen and update the value of P3. The conditional formatting would note any change to P3, and adjust the formatting.
Short answer
A custom function can't be used as a part of a custom formula in the Google Sheets' conditional formatting built-in user interface.
Explanation
In Google Sheets, a custom function is like spreadsheet built-in functions but written by the user using the Google Apps Script editor. They can't modify other objects, only return one or multiple values.
By the other hand, a custom function only is calculated when it's added to a cell or when at least one of it's parameters changes. They can't use non-deterministic functions as parameters like NOW(), TODAY(), RAND() and RANDBETWEEN().
Test
In order to test the statement in the short answer, I created a did the following:
Create a simple custom function
function two() {
return 2;
}
Add the custom function as part of a custom formula in the conditional formatting side panel
=two()=2
Result:
Nothing changed.
References
Custom Functions in Google Sheets

Google Spreadsheet Script not Updating Dynamic Info

So, i made a spreadsheet for Minecraft and 'Feed The Beast' a modpack for the game. My spreadsheet lists all the mods that are updated for the latest version of Minecraft. Recently i made a script to go out and parse pages for mod version numbers. They change hourly-daily and i rather not do it manually.
function GetVersion(url, slice, num1, num2) {
var r = UrlFetchApp.fetch(url).getContentText();
var version = r.slice(r.indexOf(slice)).slice(num1, num2);
return version;
}
In one of the cells Ill have the following
=GetVersion("http://files.minecraftforge.net", "Build 7.", 12, 15)
Now this works fine and gets me the version number im looking for. The problem is, when an update happens and a new version comes out, the parser doesn't reflect this even if i close the window and reopen the spreadsheet or reload or whatever else! If I change the above slightly, like change the 15 to 16, it will refresh, but then will be stuck there again until i manually change it again.
How do I get it so it at least refreshed when i reload the sheet?
Edit: Alright first I tried to go into reosources and triggers and make a trigger very min and everytime the doc is opened. This didn work..............
Then I tried to get clever. Noticing that the formula reevaluates whenever I change it, i surmised that the formula itself or the cell parameters needs to change in order for this to happen. So I pass a dummy parameter though in the formula and change that parameter to update the cell.
But that's annoying and make me have to edit (or press a button) just to get shit to refresh.
So i got a brainwave and Im now passing GoogleClock() in the dummy parameter. All cells now update on their own every 60 seconds. yay
Is there a better way to do this?
Using googleclock as a param is the best u can do if u want to use a custom cel formula.
Instead call an update function from a menu item and/or onOpen / time trigger.
Aside from the workaround of passing GoogleClock() as a parameter (which I agree is the best you are going to do with a custom function), the other option is to do away with a custom function, and use GAS to write the result directly to a cell, eg:
SpreadsheetApp.getActiveSpreadsheet().getRange('Sheet1!A1').setValue(version);
Then in Resources, Current project's triggers, you can set both an "on edit" and time-driven trigger (to be clear: these triggers won't work on a custom function called from a spreadsheet cell; all the "work" must be done by the script itself).