Sub topic 14
Automating notes and listing comments with scripts
This chapter assumes you can already add comments and notes by hand, know the difference between them, and have opened the Apps Script editor from Extensions > Apps Script at least once. You should be comfortable reading basic JavaScript: functions, const, arrays, and forEach.
By the end, you will be able to read and write notes with Apps Script, list a spreadsheet's comments through the Drive API, and explain why those two tasks use different tools.
Why two different tools
In earlier chapters you saw that comments and notes look similar on screen but are different objects. Scripting makes that difference concrete.
- Notes belong to a cell. The Spreadsheet service in Apps Script (
SpreadsheetApp) exposes them directly on aRange. - Comments (including threaded replies, resolved state, and assigned tasks) belong to the file. They are stored by Google Drive, not by the spreadsheet's cell grid.
SpreadsheetApphas no method for them.
So the rule of thumb is: use SpreadsheetApp for notes, and use the Drive API for comments.
| Item | Where it lives | Script access |
|---|---|---|
| Note | The cell | `Range.getNote()`, `Range.setNote()` |
| Comment | The file in Drive | Drive API `Comments` resource |
| Reply, resolved state | The file in Drive | Drive API `Comments` and `Replies` resources |
| Version history | The file in Drive | Drive API `Revisions` resource |
Reading and writing notes
A note is a plain text string attached to a single cell. The two core methods are setNote(text) and getNote().
function addReviewNote() {
const sheet = SpreadsheetApp.getActiveSheet();
const cell = sheet.getRange('B2');
cell.setNote('Check this figure against the Q3 report.');
Logger.log(cell.getNote());
}Run addReviewNote from the editor. The first run asks you to authorize the script. After it finishes, a small marker appears in the corner of B2, and the execution log shows the note text.
A few behaviors are worth knowing:
getNote()returns an empty string, notnull, when a cell has no note.setNote('')removes a note. Passingnullalso clears it.setNotereplaces the existing note. It does not append to it.- A note has no author, no replies, and no resolved state. Only the text is stored.
Working with many cells
When you handle more than one cell, use the plural methods on a multi-cell range. They return and accept two-dimensional arrays, the same shape as getValues().
function flagLargeValues() {
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('C2:C20');
const values = range.getValues();
const notes = range.getNotes();
const updated = values.map(function (row, i) {
const value = row[0];
if (typeof value === 'number' && value > 10000) {
return ['Large value: confirm with finance.'];
}
return [notes[i][0]];
});
range.setNotes(updated);
}This function keeps existing notes on cells that do not need a flag. It rewrites the whole range in one call. The single setNotes call is much faster than calling setNote in a loop, because each call to the Spreadsheet service has overhead.
Common mistakes with notes
- Shape mismatch.
setNotesneeds an array of rows, and each row is an array. A flat array such as['a', 'b']throws an error. Wrap each value:[['a'], ['b']]. - Wrong size. The array dimensions must match the range exactly. A
C2:C20range needs 19 rows of 1 column. - Overwriting by accident. Because
setNotereplaces text, read the old note first if you want to keep it.
function appendToNote() {
const cell = SpreadsheetApp.getActiveSheet().getRange('B2');
const existing = cell.getNote();
const addition = 'Reviewed on ' + new Date().toDateString();
cell.setNote(existing ? existing + '\n' + addition : addition);
}Listing comments with the Drive API
Because comments live on the file, you read them through the Drive API. Apps Script offers the API as an advanced service. An advanced service is a thin wrapper over a Google REST API that you switch on per project.
Enable the Drive service
- In the Apps Script editor, click the + next to Services in the left sidebar.
- Choose Drive API.
- Select version v3 and click Add.
The identifier defaults to Drive, which is the name the code below uses.
List the comments
function listComments() {
const fileId = SpreadsheetApp.getActive().getId();
const result = Drive.Comments.list(fileId, {
fields: 'comments(content,resolved,author/displayName)'
});
(result.comments || []).forEach(function (c) {
Logger.log(c.author.displayName + ': ' + c.content + (c.resolved ? ' (resolved)' : ''));
});
}Three details matter here.
- The
fieldsparameter is required. The Drive v3comments.listmethod returns nothing useful unless you name the properties you want. If you leavefieldsout, the call fails with an error that says the parameter is required. - The result may have no
commentsproperty. When a file has no comments, the property can be missing. The expressionresult.comments || []prevents a crash. - The field mask uses a path syntax.
author/displayNameselects one property inside the nestedauthorobject. Parentheses select several properties from each item in a list.
Run the function, then open View > Logs or the execution log. Each line shows who wrote a comment, its text, and whether it is resolved.
Choosing more fields
You can request more properties by adding them to the mask. Some useful ones:
| Field | Meaning |
|---|---|
| `id` | The comment's identifier, needed for replies or updates |
| `content` | The comment text |
| `resolved` | `true` if the thread was resolved |
| `createdTime` | When the comment was made |
| `quotedFileContent/value` | The text the comment was anchored to |
| `replies(content,author/displayName)` | The replies in the thread |
| `nextPageToken` | A token for fetching the next page of results |
Be aware that for a spreadsheet, the anchor field is an internal string. It identifies where the comment sits, but it is not a readable cell address like B2. You should not plan on turning it into a reliable cell reference.
Handling more than one page
comments.list returns a limited number of comments per call. For files with many comments, loop with pageToken until no token comes back.
function listAllComments() {
const fileId = SpreadsheetApp.getActive().getId();
const rows = [];
let pageToken;
do {
const result = Drive.Comments.list(fileId, {
fields: 'nextPageToken,comments(id,content,resolved,createdTime,author/displayName,replies(content))',
pageSize: 100,
pageToken: pageToken
});
(result.comments || []).forEach(function (c) {
rows.push([
c.author.displayName,
c.content,
c.resolved ? 'Resolved' : 'Open',
c.createdTime,
(c.replies || []).length
]);
});
pageToken = result.nextPageToken;
} while (pageToken);
Logger.log('Found ' + rows.length + ' comments.');
return rows;
}Note that nextPageToken sits outside the comments(...) parentheses in the mask. If you forget it, the loop stops after the first page and you silently miss comments.
Writing a comment report to a sheet
A common use is a summary tab that lists open comments. This function builds on listAllComments.
function writeCommentReport() {
const rows = listAllComments();
const ss = SpreadsheetApp.getActive();
const sheet = ss.getSheetByName('Comment report') || ss.insertSheet('Comment report');
sheet.clear();
sheet.getRange(1, 1, 1, 5).setValues([['Author', 'Comment', 'Status', 'Created', 'Replies']]);
if (rows.length > 0) {
sheet.getRange(2, 1, rows.length, 5).setValues(rows);
}
}The report is a snapshot. It does not update itself, so run it again, or attach it to a time-driven trigger, when you need fresh data.
Limits and gotchas
- Permissions. The script runs as you. If you can only comment on a file, the Drive call may still list comments, but you cannot expect editing features to work. Writing notes with
setNoteneeds edit access to the sheet. - Authorization scopes. Enabling the Drive service adds a Drive scope to the project. Users see a new authorization prompt the next time they run it.
- Assigned tasks. The Drive v3 comment resource gives you the comment text and resolved state. Do not rely on it to expose the assignee of a task or to create an assignment. Check the current API reference before you build anything that depends on tasks.
- Notes are not in the Drive API. Notes are part of the cell data, so
Drive.Comments.listnever returns them. UsegetNotes()for those. - Deleted and resolved comments. Resolved comments still come back with
resolvedset totrue. If you want only open threads, filter them in your code. Deleted comments are marked with adeletedfield and have no content, so request that field if you need to skip them. - Quotas. Both services have daily quotas. A report that runs every minute on a large file can hit them, so prefer hourly or daily triggers.
Connecting this to the review workflow
In the previous chapter you combined comments, tasks, and version history by hand. Scripts help at the edges of that process:
- Use notes for stable, script-written labels such as "Source: Q3 report" that no one needs to discuss.
- Use
listAllCommentsto count open threads before a milestone, and name a version only when the count is zero. - Use a trigger to refresh the report tab each morning so reviewers see current status.
Exercise
A teammate's script calls Drive.Comments.list(fileId) with no second argument and fails. What is missing, and what would you add to list each comment's text and whether it is resolved?
Show answer
The fields parameter is required for the Drive v3 comments list call. Add an options object such as { fields: 'comments(content,resolved)' } as the second argument.
Exercise
You run range.setNotes(['a', 'b']) on A1:A2 and get an error. Why, and how do you fix it?
Show answer
setNotes needs a two-dimensional array of rows. The flat array has the wrong shape. Use [['a'], ['b']].
Exercise
You want a script to print the notes on a sheet and the comments on the same file. Which service handles each, and why?
Show answer
Notes are read with SpreadsheetApp (getNote or getNotes) because they are stored with the cell. Comments are read with the Drive advanced service (Drive.Comments.list) because they are stored on the file in Drive, and SpreadsheetApp has no method for them.