Automate Individual Apps

Later in this book, I talk about system-wide automation technologies built into macOS like AppleScript and Automator, which can automate the actions of individual apps. But 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.

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 macOS or Windows. Microsoft removed VBA from Office 2008 for Mac, but brought it back in Office 2011. It’s still there in Office 2016, and presumably, it 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.)

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:

  • Perform a frequently used find-and-replace operation
  • Format spreadsheet cells according to their contents
  • Number all the instances of a certain phrase in a document
  • Reformat a table
  • Remove all the hyperlinks in a workbook
  • Change all the tab stops in the current paragraph style
  • Merge cells from two columns into a third column
  • Resize all the graphics in a document

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 Macro.
  3. In the dialog that appears (Figure 16), give your new macro a name (like Test) and click OK.
    **Figure 16:** In this window, you define a new macro before you begin recording it.
    Figure 16: In this window, you define a new macro before you begin recording it.
  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 17, along with other windows that you can ignore for now.

**Figure 17:** Here’s what the macro we just recorded looks like in Visual Basic.
Figure 17: 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.

To get out of the editor, choose File > Close.

Assign a Keyboard Shortcut to a VBA Macro

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. In Word or Excel (but not PowerPoint), follow these steps:

  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.

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 key combination!

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 macro commands. For this example, enter 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, or assign a keyboard shortcut to your macro (such as Command-Shift-V) following the instructions in Assign a Keyboard Shortcut to a VBA Macro.

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? Oh, it’s 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 25-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 an 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 capabilities in the app that don’t appear anywhere in the visible user interface. In other words, macros let you 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:

  • Macro > Calculation > Mortgage Calculator: Fill in the blanks to calculate your monthly payment.
  • Macro > Document > Create Word Frequency List: This creates a new document listing every word in the existing document (or selection) along with a count of how many times it appeared.
  • Macro > Editing > Quote Selection: Select some text and run this macro to put quotation marks around it.

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

  • Converting documents that use our highly customized styles into Markdown formatting, which we then use to create the EPUB and Mobipocket editions of our books
  • Inserting or formatting tips and notes
  • Turning selected text into a cross-reference to a bookmark elsewhere in the document
  • Checking for common errors, such as graphics with problematic names or extra spaces between words

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 destination is ~/Documents/Nisus Documents/Macros, because that’s the default location for macros and any 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.

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?

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 in 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'

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'

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 helpful, 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:

  • Save As: Command-S-A
  • Save As PDF: Command-P-D-F
  • Replace and Find: Command-R-F
  • Page Break: Command-P-B
  • 12 (font size): Command-1-2

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 18).
    **Figure 18:** Set up keyboard shortcuts here.
    Figure 18: Set up keyboard shortcuts here.
  2. In the Menu column, select the menu where the command is found.
  3. In the second column, select the command (or, if it’s not on the top level of the menu, navigate through the submenus to select it).
  4. Click in the field on the rightmost pane.
  5. Press the keyboard combination or sequence you want to use. You can include 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 suggest limiting sequences to two or three characters, plus modifiers.

    A shortcut must include Command, but it may include Shift, Option, and/or Control too. Any of these that you hold down while entering a shortcut are selected, but you can also select or deselect Shift, Option, or Control to add or remove it from the shortcut.

  6. Click Set.
  7. Repeat with any additional shortcuts you want to define. When you’re done, click the red Close button. (Don’t 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 combines two features: automatic numbers and cross-references. I’ve used both dozens of times in this book. Let me tell you why they’re great.

Nisus Writer Pro can automatically number almost anything—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 interesting 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 automatically if, later on, 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!

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 19).
    **Figure 19:** Your list style definition should look something like this.
    Figure 19: 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 have three or four numbered figures. (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!

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:

  • Adobe Acrobat Pro and Photoshop: Both of these apps let users create actions, which are basically macros—sequences of predefined steps that alter a document or image in some way. You can also install actions other people have written, some of which are fantastically sophisticated.
  • BBEdit: This splendid plain-text editor, which is designed mainly for programmers and Web designers but has also found a following among authors, has a couple of great automation features. Text factories are sequences of actions (such as find-and-replace–based on regular expressions, natch; sorting lines; changing case; and running shell scripts or AppleScripts) that you can save and run repeatedly with a couple of clicks. BBEdit also has a Text > Apply Text Filter submenu, which lists not only your text factories but also individual Automator workflows, AppleScripts, and shell scripts that can process and modify your text.
  • FileMaker Pro: This user-friendly relational database from Apple subsidiary FileMaker Inc. is deeply scriptable. You can use its own extensive built-in scripting language, or AppleScript, or the two in combination to take nearly any action when a button is pressed, a menu command is selected, or any of half a dozen other triggers occurs. Scripts can include complex logic, mathematical calculations, and numerous types of data manipulation.
  • Google G Suite: This Web-based productivity suite includes apps for editing for documents (Google Docs—somewhat like Word), spreadsheets (Google Sheets—somewhat like Excel), and presentations (Google Slides—somewhat like PowerPoint), among other tools. Lots of people do their day-to-day document editing with Google’s apps in a browser. To automate tasks in these apps, you use a scripting language called Google Apps Script. It’s based on JavaScript, and basically amounts to VBA for Google apps. But it’s even better than VBA in that it can add custom menus, dialogs, and sidebars to G Suite apps, interact with other Google services (such as AdSense and Google Drive), and quite a bit more.
  • Logic Pro X: Apple’s professional audio recording software lets you create multitrack recordings of real and virtual instruments and vocals, add effects, and mix audio every which way. It can memorize all your changes in real time—adjustments to volume, panning, equalization, effect levels, and other parameters for each individual track—and repeat those changes every time you record or play back your music.
  • OmniGraffle and OmniOutliner: These fine apps by the Omni Group use JavaScript for automation—and that works even in their iOS versions. It’s such an innovative automation technique that I’ve devoted a whole chapter to it. See Use Omni Automation.
  • Panorama: Another, even older database app, Panorama was designed for speed and flexibility. In much the same way that Nisus Writer Pro is a programmable word processor, Panorama is a programmable database—in fact, it’s a complete development environment. You can control every aspect of its operation and create enormously complex applications using its built-in programming language; with scripts written in Perl, Ruby, Python, PHP, or AppleScript; or with shell scripts. (Indeed, large portions of Panorama were written in Panorama’s programming language itself.)

    I’ve been beta testing Panorama X—a complete, modern rewrite of the app—for a number of months. I use it for, among other things, tracking royalties for all Take Control authors. I can’t say enough good things about it—it’s an insanely powerful and flexible tool that, over time, will enable me to automate a great many parts of the process of running Take Control Books.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset