sveta_d
sveta_d

Reputation: 103

Delete comments in the selected area

In Excel Online, we can select a range of the cells, right-click on it, and delete the comments that are located in this area. Is it possible to reproduce the same behavior using excel js API? If we apply context.workbook.comments.getItemByCell to a cell that has no comments, an error occurs. If we try to add a comment to a cell that already has a comment, an error occurs too.

How can we find out if there is a comment in a cell using excel js API? Do you plan to add the getItemByCellOrNullObject method for handling comments or similar methods to help avoid these inconveniences with errors?

Upvotes: 2

Views: 295

Answers (1)

Raymond Lu
Raymond Lu

Reputation: 2236

Thanks for your question, it looks to me a new API request, would you please submit your ask in uservoice at https://officespdev.uservoice.com/forums/224641-feature-requests-and-feedback?category_id=163563 and upvote your request?

A workaround that may help in your scenario is to catch the exception thrown by api “getItemByCell(cellAddress)”, and if the error is “itemNotFound”, then it means there is no comment in the cell, see below sample code.

  await Excel.run(async (ctx) => {
        var cellAddress = "Sheet1!A1";
        var comments = ctx.workbook.comments;
        try {
              var comment = comments.getItemByCell(cellAddress);
              comment.delete();
              await ctx.sync();
              console.log("Delete comment successfully!");
        } catch (error) {
              if (error.code == Excel.ErrorCodes.itemNotFound) {
                    // Handle the logic if the cell does not contain comment.
                    comments.add(cellAddress, "New comment!");
                    await ctx.sync();
                    console.log("Add comment successfully!");
              }
              else
              {
                    // Other errors.
              }
        };
  });

Upvotes: 3

Related Questions