Google Sheets Scripts: How to Write & Run Apps Script

How-to basics · Updated December 1, 2026

Writing scripts for Google Sheets means using Apps Script, a JavaScript-based language built into Google Workspace. With it, you can automate repetitive tasks like sending emails, formatting rows, or pulling data from APIs. You don’t need to install anything—just open your sheet, go to Extensions, and start coding. This guide walks you through your first script, from opening the editor to running and debugging it.

What You’ll Need

  • A Google account (free) and a web browser (Chrome, Edge, Firefox, or Safari).
  • A Google Sheet with some sample data—e.g., names in column A and amounts in column B.
  • Basic familiarity with JavaScript (variables, functions, if/else) helps, but you can copy-paste and adapt the examples here.

Step-by-Step

  1. Open the Apps Script editor. In your Google Sheet, click Extensions > Apps Script. This opens a new browser tab with a blank Code.gs file. The editor is where you write and manage all scripts for that sheet.
  2. Write your first function. Delete the default myFunction() and paste this simple script that logs the active sheet’s name:
    function showSheetName() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet();
      var name = sheet.getName();
      Logger.log("The sheet is: " + name);
    }

    Click Save (disk icon or Ctrl+S / Cmd+S). Name the project anything, like “My First Script”.

  3. Run the script. In the toolbar, select showSheetName from the function dropdown (next to the play button). Click Run. The first time, Google asks for permissions—click Review permissions, choose your Google account, then Allow. This is normal; Apps Script needs consent to access your sheet data.
  4. View the log. After it runs, click Executions in the left sidebar (or press Ctrl+Enter on Windows / Cmd+Enter on Mac in the editor). You’ll see a log entry with your sheet’s name. If you don’t see it, click the “Execution log” link at the bottom of the editor.
  5. Read data from the sheet. Now make the script actually do something useful. Replace the function with:
    function sumColumnB() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var lastRow = sheet.getLastRow();
      var values = sheet.getRange(2, 2, lastRow - 1, 1).getValues();
      var sum = 0;
      for (var i = 0; i < values.length; i++) {
        sum += values[i][0];
      }
      Logger.log("Sum of B2:B" + lastRow + " = " + sum);
    }

    This assumes row 1 has headers and numbers start in B2. Save, select sumColumnB, and run it. Check the log for the sum.

  6. Write a value back to the sheet. To output the result into a cell, use setValue(). Add this line at the end of the function (after the loop):
    sheet.getRange(lastRow + 2, 2).setValue(sum);

    This writes the sum two rows below your last data row (e.g., if data ends at row 10, it writes to B12). Run again, and you’ll see the number appear in your sheet.

  7. Create a custom menu. So you don’t have to open the editor every time, add a menu. Insert this function:
    function onOpen() {
      var ui = SpreadsheetApp.getUi();
      ui.createMenu("My Scripts")
        .addItem("Sum Column B", "sumColumnB")
        .addToUi();
    }

    Save, then run onOpen once manually (to authorize). Reload your sheet—you’ll see a “My Scripts” menu in the toolbar. Click it and choose “Sum Column B” to run the script without leaving the sheet.

  8. Set up a trigger (optional). To run automatically, click the clock icon in the Apps Script editor (left sidebar). Click Add Trigger, choose sumColumnB, select “Time-driven” and “Hour timer” (or “On open” for a one-time event). Save. Now the script runs automatically on the schedule you set.

Common Mistakes

  • Forgetting to authorize. If you see “Exception: You do not have permission to call SpreadsheetApp”, you skipped the permission step. Run the function once manually and accept the prompts.
  • Using wrong range references. getRange(2, 2, lastRow - 1, 1) means start at row 2, column 2 (B), take lastRow - 1 rows, and 1 column. If your data has blank rows, getLastRow() may return a larger number than expected, causing errors. Use getDataRange() instead if you want the entire contiguous block.
  • Mixing up sheet and spreadsheet. getActiveSpreadsheet() returns the whole file; getActiveSheet() returns the current tab. If you have multiple tabs, you must specify which one—e.g., getSheetByName("Data").
  • Not saving before running. If you change code and hit Run without saving, the old version executes. Always Ctrl+S (Cmd+S on Mac) first.
  • Using array methods incorrectly. getValues() returns a 2D array (array of rows, each row is an array of columns). So values[i][0] is the first column of row i. If you write values[0] alone, you get an array, not a number—a classic bug.

Tips

  • Use the built-in code editor’s autocomplete. Type SpreadsheetApp. and wait—a list of methods appears. This helps avoid typos and shows you available functions.
  • Test in small batches. Before running a loop on 10,000 rows, test on a copy of your sheet with 10 rows. Use Logger.log() to print intermediate values.
  • Handle empty cells. getValues() returns empty strings for blank cells, not null. If you’re summing, use Number(values[i][0]) || 0 to avoid adding text.
  • Use try/catch for error handling. Wrap your code in a try/catch block to log friendly messages instead of crashing the script.
    function safeRun() {
      try {
        sumColumnB();
      } catch (e) {
        Logger.log("Error: " + e.message);
      }
    }
  • Keep scripts short. Break big tasks into multiple functions. You can call one function from another—e.g., sumColumnB() inside onOpen().
  • Use SpreadsheetApp.flush() after writing values. This forces the sheet to update before your script continues, which is useful if you’re reading the same range later in the script.

Troubleshooting

  • Script runs but nothing happens. Check the execution log for errors. If the log is empty, you may have run the wrong function—make sure the dropdown shows the one you want. Also, if you’re writing to a cell, confirm the cell reference is correct (e.g., getRange(lastRow + 2, 2) may be off if lastRow is not what you expect).
  • “Cannot read property ‘0’ of undefined” error. This means you tried to access a row that doesn’t exist. Usually your range is too large or too small. Check lastRow and the range parameters. If your data starts at row 2, but you used getRange(1, 2, lastRow, 1), you’ll include the header row (which may be text) and cause type errors.
  • Permission denied after adding a trigger. Triggers need a separate authorization. Go to the trigger settings, click the three dots next to the trigger, and choose “Run” to re-authorize. Or delete the trigger and recreate it.
  • Script is slow. Apps Script has quotas (e.g., 20,000 reads per day for consumer accounts). If you’re processing large ranges, read all data once with getValues(), process it in memory, then write once with setValues()—don’t read/write cell by cell in a loop.
  • Changes don’t appear in the sheet. If you’re editing a different tab, your script may be operating on the wrong sheet. Use getSheetByName("YourTabName") explicitly instead of getActiveSheet().

Frequently Asked Questions

  • Can I write scripts without knowing JavaScript? Yes, for simple tasks. You can copy examples from Google’s documentation and modify values. But for anything beyond basic automation, learning JavaScript fundamentals (arrays, loops, conditionals) will save you time.
  • Will my script work on mobile? Apps Script runs in the cloud, not on your device. You can run scripts from the Google Sheets mobile app if they’re already set up, but you can’t edit code there. Use a desktop browser to write scripts.
  • How do I share a script with someone? Scripts are stored with the spreadsheet. When you share the sheet (Share button), the script is included. However, collaborators need edit access to view or run the script. You can also copy the script to a standalone project via File > Make a copy.
  • Can I use scripts to send emails? Yes, use MailApp.sendEmail() or GmailApp.sendEmail(). For example, MailApp.sendEmail("friend@example.com", "Subject", "Body"). You’ll need to authorize Gmail access—this is separate from sheet permissions.
  • What’s the difference between Apps Script and macros? Macros record your actions (like formatting) and convert them to Apps Script code. You can view and edit that code. Scripts give you full control—macros are just a starting point.
  • How do I delete a script I no longer need? In the Apps Script editor, go to the project overview (left sidebar), click the three dots next to the project name, and choose “Delete project”. This removes the script from the sheet. Be careful—this cannot be undone.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.