Edit a Google Spreadsheet using Google Apps Script - google-apps-script

I am trying to edit a google spreadsheet using google apps script. Basically, I have a cell in the spreadsheet that has the value "Pending Approval" in it. When the script is executed, I want it to change the value in that cell to "Approved". Is there a simple way to do this?

.getRange and .setValue are the methods you will want to use in whatever you are trying to do. This little function will just take the cell notation as the first argument, and then the value you want to set as the second.
function setCellValue(cellName, value) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getRange(cellName);
cell.setValue(value);
}
setCellValue("A1","Approved");

Related

I am trying to automatically apply a filter to a column - and sort the sheet in descending order by that column

I'm trying to have the spreadsheet automatically sort by Column B, in descending order. However the raw data as the "-" text so I'm using the formula in Column C "=abs(B2)" and then trying to filter by Column C instead.
I would like the sheet to automatically apply the filter and then sort when edits are made. I've been playing with the Apps Script but cannot get it to work.
Any help would be appreciated!
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
ss.getRange ("C2").setFormula("=abs(B2)");
var lr = ss.getLastRow();
var fillDownRange = ss.getRange (2,3, lr-1);
ss.getRange("C2").copyTo(fillDownRange);
}
function autosort(){
const ss = SpreadsheetApp.getActiveSpreadsheet()
const ws = ss.getSheetByName("Trustlines")
const range = ws.getRange(2,1,ws.getLastRow()-1,3)
range.sort({column: 3, ascending: false})
}
function onEdit(e){
const row = e.range.getRow()
const column = e.range.getColumn()
if(!(column === 3 && row>= 2)) return
autosort()
}
You probably do not want to get your data from IMPORTHTML. The main reason for that is that the onEdit trigger is not triggered unless the user changes some data (witch is probably not what you want to use).
What I would propose instead is to make all the calculations using Apps Script and only adding to the spreadsheet the result. This will be done following this steps:
Get the page source. This can be done using UrlFetchApp.
Interpret the source and extract the data. XmlService should allow you to do so.
Filter and sort the data. Use the native sort and filter JavaScript Array methods.
Add the result as values on the sheet.
References
Simple Triggers (Google Apps Script guide)
URL Fetch Service (Google Apps Script reference)
XML Service (Google Apps Script reference)
Array.prototype.sort() (MDN JavaScript reference)
Array.prototype.filter() (MDN JavaScript reference)

Google Sheets Timestamp on change

What I'm trying to achieve is really simple however I'm super uncomfortable with the Google Sheet Script Editor.
I want the date in a certain cell updated whenever something changes on the active sheet.
That's what I got so far:
//Timestamp on change
function timestampOnChange() {
getActiveCell().setValue(new Date());
}
However, even that already returns error messages :/
Explanation:
You need to create an onChange() trigger of a particular
function which will update a specific cell of the active sheet when the spreadsheet
changes content or structure.
The updateCell() function updates the value of B1 with the current
timestamp of the active sheet.
I would advice you to update a specific sheet instead of the active
sheet by using:
const sh = ss.getSheetByName('Sheet1');
instead of:
const sh = ss.getActiveSheet();
Solution:
In more detail, The createOnChangeTrigger() function will create
the onChange() trigger that will execute updateCell() when there
is a change in the content or structure of the spreadsheet file and in our case the active sheet.
function createOnChangeTrigger(){
const ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger("updateCell")
.forSpreadsheet(ss)
.onChange()
.create();
}
function updateCell(){
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
sh.getRange('B1').setValue(new Date());
}
Instructions:
Copy/Paste both functions in the script editor and execute createOnChangeTrigger() only once.
References:
onChange()
From the question:
//Timestamp on change
function timestampOnChange() {
getActiveCell().setValue(new Date());
}
However, even that already returns error messages
The above code returns an error because theres isn't a built-in Google Apps Script function named getActiveCell(). To get the active cell you could use
SpreadsheetApp.getCurrentCell()
or
SpreadsheetApp.getActiveRange()
or if you use an edit event object (let say that it's a assigned to e) you could use e.range
It's worthy to not that if you use setValue(new Date()) on the active cell what ever that was entered on that cell will be overwritten.
On Web Applications, a sister site of Stack Overflow, there a lot of Q/A about timestamps in Google Sheets, actually, there is tag for them ---> https://webapps.stackexchange.com/questions/tagged/google-sheets-timestamp. So far there are 102 questions with this tag.

How to change the cell value of multiple sheets in Google Sheets [Google App Script]?

I have many sheets {(for example) 01.01, 01.02, 01.03 ..... 12.30, 12.31}.
Sheets are duplicated by one sheet, so all sheets of cell address J1 is the same date value.
I want to change J1 cell value by Google App Script.
For example:
J1 value in 01.01 sheet is 2020.1.1
J1 value in 01.02 sheet is 2020.1.2
J1 value in 01.03 sheet is 2020.1.3
J1 value in 12.30 sheet is 2020.12.30
J1 value in 12.31 sheet is 2020.12.31
Here is my Google Sheet
Seeing your sheet it is in korean so I don't know exactly how you want your information to be formatted.
But what I understand is that you want to format the same cell in every sheet using the name of the sheet. I can explain how to get started in that.
function updateCell() {
const a1NotationRange = "J1"; // The range to be modified in every sheet
// Retrieve the spreadsheet
const ss = SpreadsheetApp.getActiveSpreadsheet();
// Get the full list of sheets and change the value of `a1NotationRange`
// And execute a function for every single sheet
const sheets = ss.getSheets();
sheets.forEach((sheet) => {
const sheetName = sheet.getName();
// If you want to modify the format to be inserted you should expand
// this snippet of code here.
sheet.getRange(a1NotationRange).setValue(sheetName);
})
}
The concept is very simple, get the all the sheets inside a variable. And then iterate through them to change the range reflected in a1NotationRange.
Reference:
If you are new to javascript programming you could use some of these links to guide you in this code:
forEach()
Arrow functions expressions
If you need more help using the Apps Script services:
getActiveSpreadsheet()
getSheets()
setValue()

How to set the format of a spreadsheet cell to "date" using SpreadSheetApp and google App script

I need to set the format of a cell to "date" in a google spreadsheet with google app script (preferably with the spreadsheet app), so that when a persons clicks the cell a calendar pops up.
This can be achieved with the .setNumberFormat() method.
Example
See function below (adapted from Google's documentation):
function setFormat() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var cell = sheet.getRange("B2");
// Set to date format
cell.setNumberFormat("yyyy-mm-dd");
}
Note: If you're trying to achieve this for a larger range (more than 1 cell), you'll need to use .setNumberFormats() instead, here's the documentation for that method.
References
.setNumberFormat() Documentation
.setNumberFormats() Documentation
Date and Number Formats

Can I add a formula to a google form response using Apps Script?

Apologies as I am a beginner to coding. I am interested in using Google Apps Script to automate the analysis of a Google Form response.
The simple example I have is for the spreadsheet of responses for a form asking people:
1) how many players there were?
2) where they finished [1st, 2nd, etc,]
On submission of the form I want to run a script that calculates how may points they received and inserts this value in the next available column (column E in this example).
I have tried writing my first Apps Script to automate this process, but without success.
SAMPLE CODE:
function onFormSubmit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form Responses Master");
var players = e.values[2];
var place = e.values[3];
var positionPoints = e.values[4];
var positionPoints = (players - place + 1);
return positionPoints;
}
I know there are workarounds available by creating duplicate pages, but I was hoping someone might be able to advise me on how to code a solution in App Scripts, in the hope I might get a better understanding of the coding process.
You can write your appscript in the response collector spreadsheet itself instead of writing your code in form's script editor.
So, go to your response sheet and paste this code.
function myFunction()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses Master");
var rowNo = sheet.getLastRow();
var colNo = sheet.getLastColumn();
sheet.getRange(rowNo, colNo).setValue("=(C"+rowNo+"-D"+rowNo+")+1");
}
Now, go to Resources -> Current project triggers. Click on add new and set these values in drop downs: myFunction - From Spreadsheet - On form submit.
And you are done. Whenever a new response is submitted, position points will be calculated automatically.
Here,
variable sheet gets your active spreadsheet for different sheet operations which you can perform.
rowNo and colNo as seen in the code, simply fetches the value of last row/column respectively of spreadsheet in which something is written.
And, to set formula in column 'E', you can use setValue. Hence, "=(C"+rowNo+"-D"+rowNo+")+1" will be converted to (C2-D2)+1 in case of second row and so on for next rows.
getRange is simply used to tell the script that write formula inside particular cell.