Automate Individual Apps

In the previous chapter, I told you about system-wide automation technologies built into OS X. Although these technologies (particularly AppleScript and Automator) can also automate the actions of individual apps, there’s often a better—or, at least, more thorough—way of doing that within an app itself. That’s the topic of this chapter: using apps’ built-in automation capabilities.

Due to the breadth and depth of in-app automation features, I can only provide an overview, basic instructions, and a few examples. You’ll be able to accomplish some basic tasks and discover how to learn more.

I begin with Microsoft Office, partly because of its popularity and partly because of its extensive built-in programming language. I then move to Nisus Writer Pro, the very app I’m using to type these words, to illustrate a few different forms of automation that should be useful to anyone who works with words. Then I briefly discuss Google Apps Script, a macro language for Google Apps, and list the automation capabilities of several other popular apps.

Tip: If you want to automate Apple’s iWork apps (Pages, Numbers, Keynote), you’ll need to use either AppleScript or Automator. You can learn more about AppleScript for iWork at Automating iWork with AppleScript, part of the Mac OS X Automation site.

Automate Microsoft Office

Microsoft Office—which on the Mac comprises Word, Excel, PowerPoint, Outlook, and OneNote as its main components—is one of the world’s best-known software packages. Microsoft long ago added a programming language to the suite called Visual Basic for Applications (VBA), which enables users to write macros that automate Office apps, optionally embed those macros in documents, and run them (with some limitations) on either OS X or Windows. Microsoft removed VBA from Office 2008 for Mac, but brought it back again in Office 2011. Presumably, VBA will be in future versions too. (Microsoft Office also has excellent AppleScript support, which is an alternative way to accomplish many of the same tasks.)

Note: In Office 2011 for Mac, only Word, Excel, and PowerPoint support VBA.

What can you do with an Office macro? The sky’s the limit, but here are a few simple examples, any of which could be done with a single click or keystroke:

If you use Office extensively—and especially if you share documents with Windows users—it might be worth the effort to learn a bit of VBA since (unlike AppleScript) its macros work on both Windows PCs and Macs. But let me be frank: it’s not great for beginners. VBA was designed for programmers, not for ordinary users. It won’t do you any good beyond Office apps, and unlike AppleScript, VBA would never be called “English-like.” If you don’t know much about programming already, there’s a significant learning curve.

However, there’s a sneaky way to get your foot in the door—to write a VBA macro without knowing any VBA at all. Office lets you record macros—that is, turn on recording, do some stuff while Office watches, and then turn off recording. Office then attempts to make a VBA macro out of whatever you just did, which you can then replay at will. Sometimes these macros work fine as is; sometimes they require fiddling; and sometimes you’re out of luck.

So, my advice if you want to automate an Office app is to try recording a macro first. If that doesn’t work (and you can’t easily see how to fix it), move on to Automator. If Automator won’t do what you need either, try either AppleScript (if you need more control) or Keyboard Maestro (if you want a simpler interface). Write your own VBA macro from scratch only if no other tool does the trick.

Record Macros in Microsoft Office Apps

Let’s walk through the process of recording and then playing back a simple macro. (I’ll use Word for this example, but the process is virtually identical in Excel and PowerPoint.)

  1. Open a new, blank document in Word. (It doesn’t have to be blank, but it’s easier that way for this example.)
  2. Choose Tools > Macro > Record New Macro.
  3. In the dialog that appears (Figure 20), give your new macro a name (like Test) and click OK.
    **Figure 20:** In this dialog, you define a new macro before you begin recording it.

    Figure 20: In this dialog, you define a new macro before you begin recording it.

    Tip: If you want to assign a keyboard shortcut to your macro now, you can. Before you click OK in this dialog, click Keyboard, press the desired keyboard shortcut, and click OK. But you can also Assign a Keyboard Shortcut to a VBA Macro later.

  4. Now perform some actions—click buttons, choose menu commands, run a Find/Replace, or whatever you like. For the purpose of this exercise, I suggest doing the following:
    1. Type the word First, press Tab, type Second, and press Return.
    2. Type Third, press Tab, type Fourth, and press Return.
    3. Press Command-Shift-Up Arrow to select the second paragraph.
    4. Press Command-B to turn the selected text bold.
    5. Press Shift-Up Arrow to add the previous paragraph to the selection.
    6. Select Table > Convert > Convert Text to Table and click OK.
    7. Press Down Arrow to move the insertion point below the table.
  5. Choose Tools > Macro > Stop Recording.

That’s it; you’ve recorded a macro. In theory, you can replay the exact actions you took again, at any time, in any document. So let’s try.

To play back your macro:

  1. Choose Tools > Macro > Macros.
  2. Select the macro you just recorded (it will likely be selected by default).
  3. Click Run.

If everything is working correctly, your document will get two more table rows that look exactly like the two that were already there.

Curious to know what your macro looks like in VBA? Choose Tools > Macro > Macros, select your macro, and click Edit. You see something like Figure 21, along with other windows that you can ignore for now.

**Figure 21:** Here’s what the macro we just recorded looks like in Visual Basic.

Figure 21: Here’s what the macro we just recorded looks like in Visual Basic.

Beautiful, isn’t it? No, of course not, but if you look carefully, you can probably make out approximately what the commands do. If you were so inclined, you could edit the macro right here—for example, substitute different words in the Selection.TypeText Text: lines. Then, to get out of the editor, choose File > Close and Return to Microsoft Word (Command-Q, just like Quit).

Make VBA Macros Easier to Find

Going through Tools > Macro > Macros and a separate window whenever you want to run a macro is a drag. Fortunately, you don’t have to. You can assign a keyboard shortcut to your macro, put it on a menu, or both.

Assign a Keyboard Shortcut to a VBA Macro

In Word or Excel (but not PowerPoint), you can assign a keyboard shortcut to your macro:

  1. Choose Tools > Customize Keyboard.
  2. In the Categories list on the left, select Macros.
  3. In the Commands list on the right, select the macro you want to assign a keystroke to.
  4. Click in the Press New Keyboard Shortcut field.
  5. Press the key combination you want to use. (See the sidebar Use Multi-Key Shortcuts in Microsoft Word, below, for a special tip.)
  6. Click Assign.
  7. Click OK to dismiss the window.

From now on, you can activate your macro with that keyboard shortcut.

Use Multi-Key Shortcuts in Microsoft Word

A little-known and useful fact about Word (which does not apply to Excel or PowerPoint, by the way) is that keyboard shortcuts can include sequences—to a point.

For example, you could assign Control-P,B to insert a page break (Insert > Break > Page Break). The way this would work is that you’d press Control-P, and as long as the next key you pressed within 5 seconds was a B, you’d get a page break. If you pressed any other key, or no key at all, during those 5 seconds, nothing would happen.

You’ll notice that I used Control in my example, not Command. That’s because all single alphabetic Command-key shortcuts are pre-assigned, and even though you can create your own shortcuts that override them, sequences are ignored in such cases. For example, if I assigned Command-P,B to Page Break, it would have to override Command-P for Print—but then, as soon as I pressed Command-P (and without waiting for the B), the page break would be inserted. I know, weird.

So that’s one limitation. Another is that sequences can have at most two characters (plus modifiers)—you can’t assign Control-P,B,J to a Peanut Butter & Jelly macro. Still, two-key sequences starting with Control are useful mnemonic aids.

To set one up, follow the directions above, but type the sequence (such as Control-P, followed by B) in Step 5. Word shows sequences with a comma (Control-P,B), but you won’t actually type the comma.

Nisus Writer Pro offers vastly more flexibility in assigning multi-key shortcuts. See Use Multi-Key Shortcuts in Nisus Writer Pro.

Add a VBA Macro to a Menu

Office apps don’t make it excessively easy to put your own macros on menus so you can run them with one click—but it can be done:

  1. Go to View > Toolbars > Customize Toolbars and Menus > Commands.
  2. In the Categories list on the left, select Macros.
  3. In the Commands list on the right, select the macro you want to put on a menu and drag it to the small toolbar under your main menu bar that has the names of all the menus on it (File, Edit, and so on). Keep holding the button down until you’ve reached the exact spot on a menu or submenu where you want the command to go, and then release the button.
  4. The macro may have an excessively long, clunky name like Normal.NewMacros.PastePlainText. To give it a more readable name, click on the name of the menu (again, on that small toolbar) where you put the command, and then right-click (or Control-click) the command name and choose Properties from the contextual menu. Type a new name and click OK.
  5. Click OK to close the Customize Toolbars and Menus window.

Your new macro command should be on the menu (the real menu) where you placed it.

You can even add your own menu (and name it Macros, for instance), by following the above procedure but selecting New Menu at the bottom of the Categories list and then dragging the New Menu command to the desired spot in the toolbar.

Run an Existing VBA Macro

We’ve already been using VBA, but now I want to switch gears slightly to show you how to use a macro someone else wrote—for example, something you find on a Web page.

For this example, I’ll use a macro I wrote years ago to paste whatever’s on the clipboard as plain text, so that it assumes the style of the surrounding text. If you were to do this manually, the process would be: Choose Edit > Paste Special, select Unformatted Text, and click OK. A macro can reduce all that to one click or keystroke!

To use a macro someone else has written:

  1. Choose Tools > Macro > Macros.
  2. Type a new macro name (we’ll use PastePlainText) and click Create.
  3. In the window that opens, you’ll see a placeholder template for your new macro, like so:
     Sub PastePlainText()
     '
     ' PTT Macro
     '
     '
     End Sub
    
  4. Paste or type the following in the blank space before the End Sub line:
     Selection.PasteSpecial Link:=False, _
     DataType:=wdPasteText, Placement:=wdInLine, _
     DisplayAsIcon:=False
    
  5. Your final macro should look like this:
     Sub PastePlainText()
     '
     ' PTT Macro
     '
     '
         Selection.PasteSpecial Link:=False, _
         DataType:=wdPasteText, Placement:=wdInLine, _
         DisplayAsIcon:=False
     End Sub
    
  6. If you like, you can remove the lines starting with an apostrophe; those are comment lines that don’t affect the macro’s function.

Your macro is now ready to run. You can run it using Tools > Macro > Macros, assign a keyboard shortcut to your macro (such as Command-Shift-V) following the instructions in Assign a Keyboard Shortcut to a VBA Macro, or put it on a menu (see Add a VBA Macro to a Menu).

Note: I said I “wrote” this macro years ago, but, in fact, I cheated—I recorded myself following the steps I spelled out a moment ago, and this macro is what I got!

Find Sample VBA Macros

You should be able to turn up all sorts of VBA macros with a few Web searches. Here are a few resources to get you started:

Learn More about VBA

To get help writing and editing VBA macros, try these sites:

Automate Nisus Writer Pro

Nisus Writer Pro is a powerful yet easy-to-use word processor. Wait, did I call it a word processor? That’s like saying El Capitan is a rock—it’s a bit of an understatement! Nisus Writer Pro is much more than a word processor; I like to think of it as a Programmable Everything Tool. I explain my history with Nisus (the product and the company) and why I’m so enamored of this app in my Macworld article Tools of the trade: Why I prefer Nisus Writer. For anyone who works with words, it’s an extraordinarily flexible tool—and capable enough that Take Control Books has left behind both Word and Pages and now creates ebooks (including this one) exclusively in Nisus Writer Pro. With the coupon at the end of this book, you can buy Nisus Writer Pro at a 20-percent discount.

One of the reasons I like Nisus Writer Pro so much is that it’s chock full of automation features that make my writing faster and more efficient. In this chapter I want to look at three of them: macros, multi-key shortcuts, and automatic numbers and cross-references.

Run Macros in Nisus Writer Pro

As in other apps, macros in Nisus Writer Pro let you perform a single action, or a list of actions, with a menu command or keyboard shortcut. But Nisus Writer Pro macros can do much more than run sequences of commands; they can interact with files and folders on your Mac, ask for user input, make decisions based on complex logic, and access many capabilities in the app that don’t appear anywhere in the visible user interface. In other words, by writing macros, you can create entirely new features.

Nisus Writer Pro includes over 50 preinstalled macros on the Macro menu (or its submenus). Choose any macro name to run it. Some macros assume you have text selected first; if you try to run a macro and it won’t work in the current context, it’ll either beep or display an error message.

Here are a few you might try:

Take Control authors and editors have lots of specialized macros that aid in our workflow, such as:

If you’d like to find more macros you can install and run yourself, visit Nisus Software’s Nisus Writer Pro Macros forum. (That’s also a good place to find tips on writing your own macros.)

Create Macros in Nisus Writer Pro

To make your own macro in Nisus Writer Pro, follow these steps:

  1. Choose Macro > New Macro. A new window (which looks just like a regular document window) opens.
  2. Type or paste the text of your macro. For illustration purposes, try this:

    prompt "Hello, world!"

  3. Choose Macro > Save as Macro. Give your macro a name (such as Hello) and choose a location. The ideal place to save it is ~/Library/Application Support/Nisus Writer Pro/Macros, because that’s the default location for macros and any macros that you save there will automatically appear on the Macro menu; if you save it anywhere else, you’ll have to go through extra steps (which I don’t cover here). The macro appears on your Macro menu automatically.

Now, to run your macro, choose its name from the Macro menu: Macro > Hello (or whatever you named it). You should see a little dialog with the text “Hello, world!” Click OK to dismiss it.

If you want to view or edit a macro that’s already in the Macro menu, the easiest way to do so is to hold down the Command key while choosing the macro from the menu—instead of running, it opens in a new window. You can edit it there; after you save it, choosing the macro name from the Macro menu in the normal way runs your updated version.

Tip: You can, of course, assign keyboard shortcuts to macros too. I cover that just ahead, in Use Multi-Key Shortcuts in Nisus Writer Pro.

I gave you a one-line example macro, but what else can you put in a macro? I’m glad you asked. Let me begin with the easiest approach to writing your own macros.

Simple Macros

First, the bad news: unlike Microsoft Office, Nisus Writer Pro has no recording capability—it can’t watch what you do and make a macro out of that for you. But now, the good news: it’s way easier to write macros for Nisus Writer Pro than for Word!

How easy? For the simplest things, like running menu commands, you just type a command (as it appears on a menu) on a line by itself. If the command includes an ellipsis (…), you can leave that off.

So, here’s a macro that turns the selected text bold, makes it 18 points, and then copies it to the clipboard:

bold
18
copy

And that’s a complete macro, by the way—no brackets, declarations, funky names, or obscure codes. Case doesn’t matter. (Spelling does matter!) Great, right?

Tip: When trying the macros from this book in Nisus Writer Pro, either retype them or paste them by choosing Edit > Paste > Paste Text Only (Command-Shift-V). If you paste styled text into a macro, you might encounter inscrutable error messages.

A macro can do lots of things that aren’t merely menu commands, too. Want it to type the text “Hello, world!”? Do it like this:

type text "Hello world!"

Find all instances of the word Apple?

find all "Apple"

Set the line height to exactly 17 points?

set fixed line height 17

You can construct a macro with dozens or hundreds of commands like this, one after the other, and it will execute them all with a single click.

I gave find all "Apple" as an example, but one of the most useful things you can do with a macro is automate more elaborate find-and-replace procedures—or a series of them. Nisus Writer Pro, like a few other apps mentioned in this book, lets you use a pattern-matching system known as regular expressions for finding and replacing text. (It can take those expressions even further by applying styles to portions of the expressions—a highly unusual feature.)

Any type of find or replace operation can go in a macro. For example, this macro line finds any sequence of two or more return characters and replaces it with one:

find and replace '\\n\\n+', '\\n', 'Ea'

Note: The letters E and a at the end tell the macro to perform the find and replace with two special options—using regular expressions, or PowerFind Pro, as Nisus Writer Pro calls them (E), and replacing all the occurrences in the document (a).

This one finds any sequence of two capitalized words and underlines just the first one:

find and replace '([A-Z][a-z]+)( [A-Z][a-z]+)', '\\1\\2', 'Ea-iU'

Note: The -i at the end means “case-sensitive search”; the U means “attribute-sensitive replacement.”

Complex Macros

It’s easy to make a macro that executes a series of simple commands, but you may want to do fancier things. You may want to use variables, arrays, objects, functions, loops, if/then/else conditionals, mathematical functions, string manipulation, and other sorts of things you’d normally find in a “real” programming language. All that, and much more, is well within the purview of Nisus Writer Pro macros too!

I’ve written many of these complex macros that involve serious programming, and while I can say confidently that it’s not nearly as bad as working in VBA or even AppleScript, it’s different. And the way you construct the commands and routines to do these nifty things is far from obvious.

Unfortunately, there’s not room here for me to get into the finer points of the language. You can get some guidance from the Nisus Writer Pro macro reference—choose Help > Macro Language Reference in Nisus Writer. That document contains all (well, nearly all) of the commands in the language, and a number of examples. But candidly, it wasn’t written for the layperson. The macro language itself isn’t unduly complicated, but the documentation makes it seem harder than it is. Someone ought to write a better guide. Maybe one day, somebody will.

In the meantime, I recommend the same thing for learning Nisus Writer Pro macros as I recommend elsewhere in this book for VBA and AppleScript: start with things other people have written (including the 50+ macros included with Nisus Writer Pro), try modifying them a little bit, and once you get the hang of that, start exploring new commands and features.

Use Multi-Key Shortcuts in Nisus Writer Pro

Nisus Writer Pro lets you assign a keyboard shortcut to any command, including macros you create yourself. That isn’t unusual. What is unusual, and extremely cool, is that you’re not limited to modifier keys and a single character (like Command-P or Command-Option-Shift-I). You can do all that, but you can also have keyboard shortcuts that are sequences of keys.

For example, there’s a menu command that capitalizes the first letter of each selected word: Edit > Convert > To Capitalized. You could assign Command-Control-Shift-C to it, but that’s hard to remember. What’s easy to remember is Command-C-A-P. That is, hold down Command while typing C, and then A, and then P. Cool, no?

Multi-key shortcuts are much easier to remember, because you can build in more mnemonic clues. How about:

I’m sure you get the idea. Here’s how you set up a shortcut:

  1. Go to Nisus Writer Pro > Preferences > Menu Keys (Figure 22).
  2. In the Menu column, select the menu where the command is found.
    **Figure 22:** Set up keyboard shortcuts here.

    Figure 22: Set up keyboard shortcuts here.

  3. In the second column, select the command (or, if it’s not on the top level of the menu, navigate in the submenus until you can select it).
  4. Click in the field on the rightmost pane.
  5. Press the keyboard combination or sequence you want to use. You can have shortcuts with as many characters as you like—Command-C-A-P-I-T-A-L-I-Z-E is valid. But realistically, that’s awkward to type—I recommend keeping sequences to two or three characters, not counting modifiers.

    All shortcuts must include Command, but you can optionally include Shift, Option, and/or Control key modifiers too. Any of these that you hold down while entering your shortcut are selected, but you can also select or deselect Shift, Option, or Control later to add or remove them as part of the shortcut.

  6. Click Set.
  7. Repeat with any additional shortcuts you want to define. When you’re done, click the red Close button. (Do not press Command-W, because Nisus Writer Pro will think you’re trying to assign that shortcut to the current command!)

Keyboard shortcuts are available immediately.

Use Automatic Numbers and Cross-references in Nisus Writer Pro

The final Nisus Writer Pro automation tool I want to mention is actually a combination of two features—automatic numbers and cross-references. I’ve used both dozens of times in this book. Let me tell you why they’re cool.

Nisus Writer Pro can automatically number almost anything that you like—pages, sections, lists (such as the seven steps just above), figure numbers (as seen throughout this book), tables, and the like. These numbers are variables that update themselves automatically. So, if I’m creating a list that has six items (numbered 1–6) and I press Return to create a seventh item, it’s numbered 7 automatically; if I insert, remove, or reorder part of the list, all the numbers update themselves. Similarly, if I use automatic numbering for figures, I can freely add, delete, or rearrange figures without ever worrying that the figure numbers in the captions will be out of order.

That part is useful but not terribly unusual; most word processors can do something of the sort. Where it gets cool is cross-references to the automatic numbers. For instance, I might have a graphic that’s labeled “Figure 12,” and near it I say, “see Figure 12.” I want that reference to update itself automatically if, later in the development of the book, that graphic turns out to be Figure 15 instead. So instead of just typing the reference, I insert a cross-reference to the text of that automatic number. As the figure number itself changes, so does the textual cross-reference!

Note: Nisus Writer Pro can do this trick with lots of things, not just with automatic numbers. Any time text in one part of a document changes, cross-references to that text elsewhere can update themselves. (That’s what we’ve done with all the links in this book to other topics—if I should happen to rename a heading, the text of the link updates too.)

Editor’s Note: We’ve been using figure numbering and cross-references in Nisus Writer Pro for about a year here at Take Control books, and one aspect of them that we’ve found quite refreshing (compared to our earlier tools) is that they’ve been reliable, even in 150+ page documents with lots of change tracking.

A full explanation of how to use automatic numbering and cross-references in Nisus Writer Pro would take many pages, so I’ll walk you through just one example:

  1. Begin by creating a new list style, just for figure numbers. In a Nisus Writer Pro document, choose Format > Lists > Edit List Styles.
  2. Click the plus button at the bottom and choose List Style from the pop-up menu. Name it Figures, leave the Kind set to Numbered, and click Create.
  3. In the sample text area on the right side of the window, select Level 1. Then, in the Lists palette (if you don’t see it, choose Window > Palettes > List), click in the Before Text field and type Figure followed by a space. In the After Text field, type a colon (:) followed by another space (Figure 23).
    **Figure 23:** Your list style definition should look something like this.

    Figure 23: Your list style definition should look something like this.

  4. Choose View > Page View to return to editing your document.
  5. Insert a graphic (or just type some text, pretending that it’s a graphic) followed by Return. Type a caption in the paragraph beneath that line, such as This is the caption.
  6. With your insertion point still in the caption paragraph, choose Format > Lists > Figures to apply the Figures list style. In so doing, the caption will be preceded by “Figure 1: ”.
  7. Repeat Steps 5 and 6 a few times, so you that have three or four numbered figures. (Note that if you press Return at the end of a list paragraph, Nisus Writer Pro assumes you want that next paragraph to be in list style too. You can override this by choosing Format > Lists > Use None, or by applying a paragraph style, such as Normal.)
  8. Somewhere else in your document, in an ordinary paragraph, type See and a space. Choose Insert > Cross Reference. Make sure the Insert Reference To pop-up menu says List Item, the Display Text pop-up menu says List Item Number, and the two checkboxes are deselected. Select Figure 2 in the list and click Insert.

    Your text should now say “See Figure 2”.

  9. Now make a change to your document so that Figure 2’s number changes—for example, remove the caption for Figure 1, or add another captioned figure before Figure 2.

You should see that the caption’s figure number updates itself, and the reference to that caption in the text updates itself to match!

Note: What I just presented was a distinctly oversimplified version of what we do for Take Control books, but it should demonstrate the basic principles.

Discover Other Internally Scriptable Apps

You’ve seen that Microsoft Office and Nisus Writer Pro have built-in scripting languages, in addition to being controllable by AppleScript and external macro utilities. But you may be wondering: is that it? Are there no other Mac apps that have internal macro or automation features?

Indeed there are others! Here are a few prominent examples: