First, go ahead and create a new Google Sheet. I created one called First Apps Script.
Then, select Extensions > Apps Script.
This will open a new project in the Apps Script editor.
Give your project a name by clicking on “Untitled project”.
There are three main sections in the Apps Script project UI.
-
The files in your project are displayed in a sidebar on the left.
-
If you select a file, its contents will be displayed in a code editor that occupies most of the screen.
-
There is a toolbar above the code editor.
You’ll notice the following code in the editor:
function myFunction() { }
A function is a piece of code that has a name. You can run (or execute) this piece of code elsewhere in your program by using its name. You can also run a function by selecting its name in the dropdown menu in the toolbar and clicking the Run button.
Right now, running this function will not do anything. This is because the function myFunction
is empty. There is nothing for it to do when you run it. Let’s change that.
Add the following code between the two curly braces {
and }
.
Logger.log(101);
GAS – Creating your first Apps Script
A log is like a diary for your code. It is used to record what your code did. We’re using it to record the number 101. That’s not super useful but that’s OK. You’ll eventually learn how to use it.
Note
-
Ensure that the “L” in Logger is in uppercase. Names in JavaScript are case-sensitive. Logger is not the same as logger.
-
Ensure that the line ends with a semicolon (;).
The editor should have the following code in it.
function myFunction() { Logger.log(101); }
Indent the code inside functions
Did you notice that I added two spaces to the left of [code]Logger.log(101);[/code]? This makes it easier to read the code inside functions (especially when a function has multiple lines of code within it).
Now save your script and then try running myFunction
again by clicking the Run button.
Your script will run and will record 101.0
to the execution log. You’ll also see the time at which the log entry was made. Click [X] to close the window.
GAS – Creating your first Apps Script
You can open or close the execution log by clicking on the Execution log button.