1

I have a table within a Google Document (NOT sheets). I have created a custom menu and it will have a list of options. The goal is when the user selects one of the options, it will change the background color of the active cell (determined by where the cursor is). I attempted the below code and it ran with no errors, but it does not change the background color. Any ideas? Thanks!

function onOpen() {

      var ui = DocumentApp.getUi();

      ui.createMenu('Change Colors')
      .addItem('Low', 'LowFunction')
      .addToUi();
    }

    function LowFunction() {
      DocumentApp.getUi()
      var document = DocumentApp.getActiveDocument();

      var SelectedCell = document.getCursor().getElement();
      var range = SelectedCell.setBackgroundColor('#ffffff');
    }

For some additional information, if I add the following line of code:

var SelectedCell = document.getTables()[1].getCell(1,0).setBackgroundColor('#000000');

It will change the background color of a particular cell...but I just need this code to change the color of the currently selected cell if possible.

1 Answer 1

2
  • You want to change the background color of the cell when the cursor position is staying in the cell.
  • You want to achieve this using Google Apps Script.

If my understanding is correct, how about this modification?

Modification point:

  • In order to check whether the cursor position is in a cell, it checks the parent of document.getCursor().getElement(). Because the element type is a paragraph when the cursor is staying in a cell.

Modified script:

function LowFunction() {
  var document = DocumentApp.getActiveDocument();
  var cursor = document.getCursor().getElement();
  var SelectedCell = cursor.getParent();
  if (SelectedCell.getType() == DocumentApp.ElementType.TABLE_CELL) {
    SelectedCell.asTableCell().setBackgroundColor("#808080");
  }
}
  • In this srcript, the background color of cell is changed to gray color.

References:

If I misunderstood your question and this was not the result you want, I apologize.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, that's what I was missing! This is exactly what I needed and it works perfectly. Thanks so much for the thorough explanation!
@hunter21188 Thank you for replying. I'm glad your issue was resolved. Thank you, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.