To add a custom function to a Google Sheet using Apps Script, you can define a JavaScript function and use the @customfunction
JSDoc annotation. Here’s an example code snippet:
/** * @customfunction */ function helloWorld() { return 'Hello, world!'; }
In this code, the helloWorld
function is defined as a custom function using the @customfunction
JSDoc annotation. This annotation informs Apps Script that the function is intended to be used as a custom function in Google Sheets.
The function itself can contain any desired logic. In this example, it simply returns the string 'Hello, world!'
.
To add this custom function to a Google Sheet:
- Open the Google Sheet.
- Click on “Extensions” in the top menu.
- Select “Apps Script” to open the Apps Script editor.
- In the Apps Script editor, paste the code that defines the custom function.
- Save the project by clicking on the floppy disk icon or by using the shortcut
Ctrl + S
. - Close the Apps Script editor.
After adding the custom function, you can use it in your Google Sheet just like any other built-in function. To use the helloWorld
function in a cell, enter =helloWorld()
in the cell, and it will display the message 'Hello, world!'
.
Note that it may take a few moments for the custom function to become available in the Google Sheet after you add it in the Apps Script editor.
You can define multiple custom functions within the same Apps Script project. Each function should have the @customfunction
annotation to indicate that it’s a custom function.
Feel free to modify the code and function name to suit your specific requirements and add any desired logic to your custom function.