As our list of editing macros in Microsoft Word grows, we’ll inevitably want to automate the process of assigning keyboard shortcuts to them in part because the shortcuts are occasionally reset by Word. Why not make it as easy as possible? With the help of some utility functions, this macro enables adding shortcuts in Word VBA using simple text descriptions of the shortcut and the macro or Word command name.
Thanks for your interest
This content is part of a paid plan.
Assign an easy standard shortcut
Assigning actions to run when a given keyboard shortcut is pressed is called “key binding”. In Microsoft Word, we generally bind shortcuts to our own editing macros or perhaps to standard Word commands. Of course, the purpose is to make them faster and easier to use and make our editing time more productive.
Key binding assignments are a little clunky in Word VBA, so we previously created a slightly more general shortcut assignment macro that interprets most shortcut combinations on a typical computer keyboard using tabulated key constants. However, it would be more convenient if we could also interpret plain text shortcuts in a format like “Control+Shift+A”, and let the macro determine the main key constant. Not that the previous macro is difficult to use, but the improvement saves us from looking up a constant in a table, and the improved simplicity is appealing.
Keyboard shortcuts organization series
The current article is part of a series of mostly member articles to help organize and quickly reassign our keyboard shortcuts:
- Simpler approach to get a keycode for any key combination (lacks error checks), or use the more concise but programmy version to get a keycode for any key combination (includes error checks and allows all four modifier keys on a Mac)
- Function that validates whether isolated keys are allowed for a tentative keyboard shortcut
- Macro assembles the pieces to automatically assign or reset keyboard shortcuts for macros or Word commands. This one is a little more general than the "easy" version below, but it works for any key combination allowed by Word for Windows or Mac including any special keys.
For the easiest shortcut (re)assignments using alphanumeric or function keys, we need two extra utility functions:
- Function that reads a main key from some shortcut text and returns the key constant
- Function that reads a function key from some shortcut text and returns the key constant
- Macro to assign easy shortcuts for alphanumeric or function main keys (this article)
Get the main key from shortcut text
We want to interpret full keyboard shortcuts as plain text like “Control+Shift+A”. This is probably the most common form to write shortcuts where the main key is the last character of the text. A common abbreviation for function keys is “F2”, so another convenient form for some text shortcuts includes combinations like “Command+F2”.
Convenience usually comes with a higher price tag (prep work in this case), so we worked ahead to implement the two utility functions to facilitate this macro (see series note above), but the works pays off with simple shortcut assignments. We also make use of the more general shortcut assignment version to minimize the number of steps in this macro.
A little terminology
A shortcut is the unique combination of keys used to invoke a specific macro or command.
Control, Alt, and Shift are modifier keys in Windows. On a Mac they are Command, Control, Option, and Shift.
The main key is the key we combine with some combination of modifier keys to create a unique shortcut.
A special key is any key other than an alphanumeric one.
Limitations
Assigning keyboard shortcuts to our own editing macros is great, but some limitations exist.
Not all key combinations work
Unfortunately, not all key combinations will work in Word, and valid combinations differ between Windows and Mac. We basically need to test any unusual combinations. See the previous article for more discussion on this topic.
The Function (Globe) key is not accessible for Word shortcuts for Mac, but menu commands may be set up as custom system-level shortcuts.
No parameters or functions (mostly)
We cannot assign a shortcut to any function nor to a macro that has any parameters …
Uhhhh, mostly, please don’t make me talk about—okay fine.
Clunky text parameter … but not really
We can provide a key binding with a single plain text parameter (yeah, just one and no numbers or any other data type), but it is the epitome of clunky programming (bad VBA! No treat for you). Accessing the argument inside the macro is awkward at best, and it gets worse if you need more complicated input.
Ughhh. Just avoid it.
Voice command option (Windows only)
On the positive side, we can sidestep the parameter restriction if we’re willing to invoke our macros using voice commands in Dragon Professional scripting (see other articles here for an introduction) which also uses VBA, but setting everything up requires additional work, and the application is not cheap. It’s quite convenient though. Unfortunately, this application is only available for Windows.
Be careful when using no modifier keys
Secretly, most keys can also be assigned to a shortcut without modifier keys … but this is probably dangerous since it would change how your keyboard works by default inside Word. It’s safest to save isolated keyboard shortcuts for the function keys, unless you’re sure what you’re doing. Similarly assigning a macro to only Shift+SomeKey is also questionable since most keys already have a defined action for this combination.
Macro skeleton
The macro skeleton for this alphanumeric shortcut assignment macro is:
We’ll trivially modify it at the end to create a shortcut for a standard Word command.
Neither macro is a function, so they return no value. The two macros are almost the same, so we’ll focus on the first one until the end.
Parameters
Both parameters are plain text and declared “As String”. The first is the text shortcut which we name Shortcut. Then we need the name of the macro to run when the shortcut is pressed which is stored in the SMacro parameter. In the sibling macro for Word commands, we trivially change the second parameter to SCommand just to be clearer. Each of these variables may be given to the macro as “plain text in double quotes” or via another String variable.
I like to name my text variables starting with an “s” or “S” (capital first letter indicates the macro will not change the value inside), but VBA doesn’t care as long as we don’t use one of its reserved words like Selection or String.
Get the easy key code
We first define our working key variable which we’ll call myKey. It will store a value from the WdKey enumeration table corresponding to the main key identified in the shortcut text.
Since any of the valid key constants for this macro are in the WdKey table, we use a WdKey number type. Also, the two utility functions mentioned below return a WdKey number type, so we might as well be consistent.
VBA enumerations are essentially constant tables with easy-to-read names, but we can do other things like use them as a number type also. Unfortunately, VBA doesn’t restrict any assigned variable values to included constants which half defeats the point.
In the overall key binding task, a Long number type would be okay because the key binding add method requires a Long type for its KeyCode option (see previous article if you’re interested). Word VBA automatically converts between Long and WdKey number types anyhow, so the distinction doesn’t matter much. Using WdKey here is more specific which is a tiny bit clearer.
Previous main key functions
We did the prior work to get the key values from shortcut text, so let’s briefly review these functions before we assemble the shortcut assignment macro.
Get an alphanumeric main key
The first utility function reads the last character of some shortcut text and calculates the equivalent WdKey table constant.
The Shortcut must include the alphanumeric key as the last character since that is the typical format. Any prior modifier keys or other characters are ignored.
Get a function key main key
The second main key function looks for a function key abbreviation at the end of the text Shortcut.
This version is only checked if an alphanumeric key above is not found but see below for how we implement this check.
Invalid key value
Each main key function returns a value of wdNoKey from the WdKey table if it cannot find a valid key.
Get the alphanumeric key constant
We first check whether an alphanumeric character is at the end of the Shortcut argument. We store the key result in our key value variable.
Check alphanumeric key constant
A conditional statement to check for a valid main key looks like:
The specific condition for a missing main key in the shortcut text is whether myKey is equal to the wdNoKey constant.
An equals = sign between values results in a True or False (Boolean) condition if it’s used inside a conditional statement.
Get function key constant
If no alphanumeric main key exists, then look for a function key.
Since we only have one relatively short command, we can use the more compact If statement notation to keep it on one line.
Basic error checks
We should always be proactive with catching errors since it will often save us time and trouble later.
Assigning the macro?
Giving an invalid key code to a key binding assignment would cause an error and crash the macro, but we went into some detail about this issue in the previous article when assigning a special key shortcut. That function already handles a few serious shortcut assignment errors, and since we’re using it, we can also defer handling some key code problems to that macro.
However, we should not be entirely neglectful about possible errors here since it’s useful to give a specific error message in this macro about which shortcut assignment caused an error.
Invalid key result
One problem we should check is if both utility functions fail to find a valid main key in the Shortcut text. We already checked the alphanumeric key value before attempting to get a function main key. As a result, we also need to check myKey for a wdNoKey value afterward. If looking for this function main key also fails, we give an error message and exit the macro immediately.
Again, the specific condition is whether myKey has the wdNoKey constant value from the WdKey table.
This is just a logical error at this point in the macro as opposed to a “runtime” error that will crash the macro, so we only need to notify the user and exit the function.
Empty shortcut argument?
We would normally verify the Shortcut text argument (a variable value provided to a macro or command) includes something before using it, but we’re passing it to the utility functions that already have their own error checks on this variable. Thus, we can omit any such extra checks here and use the return value as an indicator of whether either main key was detected. An empty Shortcut variable would have resulted in a value of wdNoKey for myKey anyways.
Empty macro argument?
It is difficult to validate whether a general macro name is present in our library, but an empty macro name is easy to catch and would definitely cause an error when trying to assign it to a shortcut. Technically, this error would already be caught in the more general shortcut assignment macro we call since it already checks for any runtime errors, but it only takes a moment to verify the macro name here.
An empty macro name is literally an empty string “” in double quotes, so we can just check if SMacro is empty using an equals = sign.
Remember an equals sign is a True or False (Boolean) condition when used in an If statement. We just need to include this with the previous error check where we checked for no detected alphanumeric or function main key. Since either condition is a problem, we need an Or operator.
Our revised conditional statement for the error checks is:
Error message
We use the standard VBA MsgBox function to pop up a dialog box with a relevant message. An example error message is:
The function needs a text string for the message. The above uses plain text in double quotes along with string variables, so we “added” (called concatenate for text) them together with plus + signs. VBA interprets we meant to jam the text together into a single string. MsgBox has other options to prettify the dialog box, but we’re just using a plain message for simplicity.
The more detailed we are with error messages, the more useful they are when a problem occurs. Here we’re just telling the user the failed shortcut assignment and the macro name.
Exit macro
We don’t want to attempt to assign a shortcut if there is no main key detected, so we exit the macro (called a “subroutine” or Sub for short) immediately.
Assign shortcut
If we make it to this point in the macro, the main key is valid. The previous special key version of the function is:
Macro parameters
The special key shortcut assignment macro parameters are:
- Modifier keys should be plain text.
- MainKey is a constant either from either the WdKey (mostly) or the VBA KeyCode table.
- Macro name should be plain text which is the literal name of the macro in the VBA project.
- The KeyCategory constant is from the WdKeyCategory enumeration table. Usually, this is wdKeyCategoryMacro or wdKeyCategoryCommand.
The VBA KeyCode table is basically just for the arrow keys, but the other redundant key constants also work. No special keys like arrows are used in the current shortcut assignment macro. Available macros to bind to a shortcut include any stored in your Normal.dot template or the current document.
Our arguments
For our current macro, the respective information is:
- The Shortcut argument includes the modifier keys, so we can just provide that argument. The general shortcut assignment macro will ignore the extra main key information at the end.
- The MainKey variable corresponds to our current main key constant which we determined above and stored the result in the myKey variable.
- The macro name was provided to this shortcut assignment macro as SMacro. We pass it as the third parameter without any modifications.
- The macro category is wdKeyCategoryMacro for this version. The follow-up version to assign standard Word commands will use the wdKeyCategoryCommand.
Make assignment using the previous function
Finally assign the shortcut using our specific argument values.
Again, this function does its own error checking, so some assignment errors may be caught there.
Final simple keyboard shortcut assignment macros
These two versions apply the above steps to both Word macros and any standard Word commands.
Assigning an easy shortcut to a Word macro
Putting the steps together to assign shortcut to our own editing macros, we get:
Assigning an easy shortcut to a Word command
Unfortunately, assigning a shortcut to a Word command is slightly different. Enough so that it’s easier if we just create a different macro. Including an optional parameter for the key category would be messier and violate the spirit of an "easy" shortcut assignment macro. The overlap is reasonable consisting of seven nearly identical lines along with some comments.
Since we’re creating a separate macro, we further change the second parameter name and the error message text to be a little clearer.
Examples
The whole point of these macros is making it easier to assign shortcuts. Here is how we can use it to assign one to our own macro or a Word command.
This is about as easy as it gets, and most macro or command shortcuts may be assigned with this format using these functions.
CutSentence is a custom macro that cuts the current sentence (or all partially selected) to the clipboard. OutlinePromote is a standard Word command to do just that. It promotes the current paragraph (or headings of a selection). The above command assignment doesn't technically reassign the shortcut, but my overall list of shortcut assignments overrides the existing standard Word shortcut of Alt+Shift+Left arrow in Windows. Specifically, my setup uses Alt+Shift+Left arrow to move a sentence left in a paragraph.
Overriding existing shortcuts
In addition to creating new keyboard shortcuts, these macros along with the previous special key versions will reassign existing shortcuts which includes overriding any standard Word shortcuts. This a positive feature in my opinion since many of the standard keyboard shortcuts are based in antiquity—well, it feels like it—and not really worthy of the immediate access a shortcut provides except for specific users.
- How often do most of us create new documents from inside Word? Yeah, it happens, but does it really justify a shortcut?
- What about trademark or copywrite symbols as shortcuts … really? Maybe for a few users, but they also exist as AutoCorrect entries, so they’re redundant redundant.
- If you find yourself regularly adjusting multiple paragraph or font formatting attributes with shortcuts, you should probably look into using styles.
Many standard shortcuts such as bold, copy, save, and undo are so common through various applications they should probably be left unchanged. Some depend on the type of work like mail merging or table manipulation, so they can be overridden by other users. Others are useful occasionally, but the list of questionable standard ones is kind’a long. Plus I don’t like the assignments for some of the more useful standard Word shortcuts, so it’s nice to be able to quickly reassign them to something more convenient.
Each author has a personal workflow, of course, so there will be variations of perceived importance, but only so many shortcut combinations exist. The most used macros or commands should occupy those precious positions at your fingertips in your progress toward making Word work your way.