Google Sheets Script Functions: Create Custom Formulas
In this article
To create a custom function in Google Sheets, open the Apps Script editor via Extensions > Apps Script, write a JavaScript function that returns a value, save the project, and call that function in any cell using the equals sign (e.g., =MYFUNCTION(A1)). This allows you to perform complex calculations, data manipulations, or API calls that standard built-in formulas cannot handle.
What You'll Need
- A Google account with access to Google Sheets.
- A web browser (Chrome is recommended for the best Apps Script editor experience).
- Basic familiarity with JavaScript syntax (variables, return statements, and basic math operators).
- An active internet connection to save and run scripts in the cloud.
Step-by-Step
- Open Your Spreadsheet: Launch the Google Sheet where you want the custom function to operate. Ensure you have editing permissions for this file.
- Access the Apps Script Editor: In the top menu bar, navigate to Extensions > Apps Script. This will open a new browser tab containing the Google Apps Script environment. Note that menu labels may differ slightly depending on your region or account type.
- Name Your Project: Click on the text that says "Untitled project" at the top left of the editor and give it a descriptive name, such as "CustomFinancialFunctions" or "DataCleanupTools". This helps you organize your scripts if you have multiple projects across different sheets.
- Write the Function: In the code editor window, you will see a default function called
myFunction(). You can delete this or write your own below it. A custom function must follow a specific structure: it must be a JavaScript function that takes arguments and returns a value. For example, to create a function that calculates a 15% tip on a bill, write:function CALCULATETIP(amount) { return amount * 0.15; } - Handle Multiple Inputs: If your function needs more than one piece of data, add more parameters. For instance, if you want a function that calculates a custom tax rate based on a cell value, use:
function APPLYTAX(amount, rate) { return amount * rate; } - Save the Script: Click the disk icon (Save project) in the toolbar or press Ctrl+S (Cmd+S on Mac). The script will not be available in your spreadsheet until it is saved.
- Test the Function in the Sheet: Return to your Google Sheet tab. Click on an empty cell and type the equals sign followed by your function name exactly as written in the script (case-insensitive in the cell, but best practice is to use uppercase for visibility). For example, type
=CALCULATETIP(100)or=CALCULATETIP(B2)and press Enter. - Verify the Result: The cell will briefly display "Loading..." while the Google servers execute the JavaScript and return the value to your sheet. If the math is correct, the result will appear in the cell.
Common Mistakes
One of the most frequent errors is forgetting the return statement. In standard Apps Script macros (like those that format cells), you don't always need a return value. However, for a custom function used in a cell, the function must return a value. If you omit return, the cell will simply display "undefined" or remain blank.
Another common mistake is attempting to use "side-effect" methods. Custom functions in Google Sheets are designed to be "deterministic," meaning they take an input and return an output. They cannot modify other cells, change the background color of a range, or delete rows. If your script tries to use spreadsheet.getRange('A1').setValue('Hello') inside a custom function, it will fail with an error because custom functions are read-only regarding the rest of the spreadsheet.
Naming collisions are also common. If you name your custom function the same as a built-in Google Sheets function (like SUM or AVERAGE), the built-in function will usually take precedence, or the script will behave unpredictably. Always use a unique prefix or a descriptive name that doesn't overlap with standard formulas.
Finally, users often forget that custom functions are slower than built-in ones. Calling a custom function in 5,000 different cells can cause the sheet to lag or hit the "Loading..." timeout limit. To avoid this, try to write your function to handle arrays of data rather than single cells.
Tips
Use JSDoc for Help Text: You can add a description to your function that appears when other users start typing the formula in a cell. To do this, add a comment block directly above your function using this format:
/**
* Calculates a 15% tip on a given amount.
*
* @param {number} amount The total bill amount.
* @return The calculated tip value.
* @customfunction
*/
function CALCULATETIP(amount) {
return amount * 0.15;
}
Adding @customfunction tells Google Sheets to include this function in the autocomplete suggestions.
Handle Arrays for Performance: Instead of dragging a formula down 100 rows, you can write your function to accept a range (an array of arrays) and return an array of results. This is called "batching" and significantly reduces the number of calls to the script engine. Use a map function in JavaScript to process each row of the input range and return the entire processed array at once.
Use Try-Catch Blocks: To prevent your spreadsheet from filling up with ugly #ERROR! messages when a user enters invalid data (like text in a math function), wrap your code in a try-catch block. Return a user-friendly message like "Invalid Input" instead of letting the script crash.
Troubleshooting
If your function is not working, start with the simplest check: Refresh the page. Sometimes the connection between the sheet and the script project needs a reset after a save. If the cell displays #NAME?, it means Google Sheets cannot find a function with that name. Double-check the spelling in both the script editor and the cell, and ensure the project was saved.
If you see #VALUE!, the script is running but returning a data type that the cell cannot handle, or the input provided to the function is not what the code expects (e.g., passing a string to a function that performs multiplication). Use console.log() in the Apps Script editor and check the "Executions" tab to see what values are actually being passed into your function during runtime.
If you encounter a "Loading..." message that never disappears, you may have hit a timeout. Custom functions have a maximum execution time (usually 30 seconds). If your script is performing a heavy calculation or fetching data from an external API, it may be timing out. To fix this, optimize your code or break the calculation into smaller parts.
If the script works for you but not for someone you shared the sheet with, check the permissions. While custom functions generally run under the authority of the person who owns the script, some advanced services (like fetching data from an external URL via UrlFetchApp) may require the user to authorize the script the first time it runs. They may need to run a manual function from the editor once to trigger the OAuth permission pop-up.
Frequently Asked Questions
Can a custom function send an email?
No. Custom functions used in cells cannot perform actions that require authorization to modify your account or send data, such as sending emails or accessing your calendar. To send emails, you must create a separate script function and trigger it via a custom menu button or a time-based trigger.
Do custom functions update automatically?
Custom functions recalculate when their input arguments change. However, they do not update based on time (like the NOW() function) or based on changes to cells that aren't explicitly passed as arguments to the function.
Is there a limit to how many custom functions I can use?
While there is no hard "count" limit, there are quotas on total execution time and the number of simultaneous calls. If you have thousands of custom functions in one sheet, you will likely experience significant performance degradation.
Can I use external JavaScript libraries?
You cannot import external JS files via <script> tags as you would in a webpage, but you can add "Libraries" in the Apps Script editor by providing the Script ID of another project. This allows you to share code across multiple spreadsheets.
Can custom functions access other sheets in the same file?
Yes, but not automatically. You must pass the data from the other sheet into the function as an argument. For example, if you want to use data from "Sheet2", your formula should look like =MYFUNCTION(Sheet2!A1:B10).