Andre Nevares
Andre Nevares

Reputation: 743

How to create a macro in Google Docs

I am tired of using Microsft Word.

I really like Google Docs. But I need to automate some things.

What do I want

I want to create a simple shortcut that automates some styles.

  1. on a document I will type a text.
  2. I select the Text
  3. I press a custom shortcut
  4. The text is set to blue and bold.

Why am I asking

There is a lot of good tutorials and documentation for automating Google Spreadsheet. I tried to find how to record a macro on Google Docs, and many variations. I just can not find a way to do it.

I have searched Stack Overflow, and again I cannot find.

This kind of automation, I think it is easy, but will save a lot of my time when keeping notes.

Upvotes: 3

Views: 9349

Answers (1)

Cooper
Cooper

Reputation: 64062

function setStyleBoldAndBlue() {
  const doc=DocumentApp.getActiveDocument();
  var BoldBlue={};
  BoldBlue[DocumentApp.Attribute.BOLD]=true;
  BoldBlue[DocumentApp.Attribute.FOREGROUND_COLOR]='#3c69f2';
  let selection=doc.getSelection();
  if(selection) {
    var selectedElements = selection.getRangeElements();
    for(var i=0;i<selectedElements.length;i++) {
      var selElem = selectedElements[i];
      var el = selElem.getElement();
      var isPartial = selElem.isPartial();
      if(isPartial) {
        var selStart = selElem.getStartOffset();
        var selEnd = selElem.getEndOffsetInclusive();
        el.asText().setAttributes(selStart, selEnd, BoldBlue);
      }else {
        var selStart = selElem.getStartOffset();
        var selEnd = selElem.getEndOffsetInclusive();
        el.asParagraph().setAttributes(BoldBlue)
      }
    }
  }
}

function menu() {
  DocumentApp.getUi().createMenu('MyMenu')
  .addItem('Bold and Blue', 'setStyleBoldAndBlue')
  .addToUi();  
}

function onOpen() {
  menu();
}

You can access through the MyMenu or attach it to a button. It's not a macro. It's a script.

Upvotes: 3

Related Questions