Word Macros and Visual Basic for Applications (VBA) FAQ
Beginners' tips
How to modify a recorded macro
What do I do with macros sent to me by other users to help me out?
I don't know how to install them and put them to use
What are the underscores _ at the end of lines of code there for?
Getting to grips with VBA basics in 15 minutes
Creating a macro with no programming experience using the recorder
How to assign a Word command or macro to a toolbar or menu
How to assign a Word command or macro to a hot-key
Assigning custom button images to your toolbar and menu buttons
How to get a menu button that is assigned to a macro to display the keyboard shortcut on the menu
Making the transition from WordBasic to VBA
Why variables should be declared properly
How to prevent other users from seeing and changing your VBA code
Run a macro when a user double-clicks a button in the document
Enable a user to double-click text in a document to change its value
Eg: change a “Y” to an “N” and then to a “?” and then back to a “Y”
Eg: from an I-beam to an hourglass and back
Export all the code from a code module to a text file
When to use parentheses to enclose subroutine and function arguments
The art of defensive programming
Or how to write code that will be easy to maintain
Distributing macros to other users
The best way to set a timer to time your macros
Returning information
How to check whether Word is open
Determine whether the insertion point is located at the end of a document
Detect whether a table cell is empty
Determine the page number at the current cursor position
Determine the number of pages in a document
Determine the position of the cursor on the page in points
(72 pts. = 1 inch = 2.54 cm)
Determine the index number of the current paragraph, table, section ...
Or of any object that has a Range property
Determine whether the selection is at the start of a paragraph
Or of the current table, or section – or of any object that has a Range property
Detect whether the first character in a selection is alphanumeric
Working with bookmarks
Inserting text at a bookmark without deleting the bookmark
How to create a menu to navigate to the non-hidden bookmarks in a document
For a ready-to-use add-in with macros that can extract acronymns, bookmarks, comments and tracked changes, see the free DocTools ExtractData add-in.
Working with built-in dialogs
Calling FileOpen dialog in VBA does not allow opening of multiple files
How to change the directory of the Save As dialog
Passwords not saved when calling FileSaveAs dialog from VBA
Force the user to save documents into a particular folder or a subfolder of that folder
How to get the full path from the SaveAs dialog
Force the File New dialog to display in List view
Intercept the Keyboard... button on the ToolsCustomize dialog box
Working with events
Run a macro automatically when Word starts or quits
Run a macro automatically when a document is created, opened or closed
Writing application event procedures
Or how to intercept events affecting any open document, such as the user changing focus from one document to another
Intercepting events like Save and Print
A Pseudo DocumentBeforeClose Event
Or: How to perform validation on a document when the user tries to close it.
Assigning a macro to the tab key
Change the behavior of the tab key inside a table cell
Prevent a user from interrupting a macro with Ctrl+Break
Prevent a file from showing up on the recently used files list
How can I prevent users from editing the header of a document in Word 2000 or higher?
How can I prevent users from editing the header of a Word 97 document?
Working with properties
How can I get access to the Document Properties of a Word file without opening the document?
How to use a single VBA procedure to read or write both custom and built-in Document Properties
Highlight any misspelled words, so that unrecognized words stand out prominently on a printout
Clear all highlighting from a document
Turning “Allow spacing between cells” off with VBA in a Word 2000 table
Working with printers
How can I get a list of the available printer names?
How to find out whether Word has finished printing
How to use VBA to set duplex printing on or off
Macros for booklet printing in Word 2000
How to set the paper tray to be used when printing
Changing the selected (current) printer in Word without changing the system default printer
Print all documents in a given folder to a single print file
How can I print colored text to a mono printer in pure black & white (no shades of grey)?
Paragraph borders lost when printing from a VBA macro
Working with ranges and selections (not including Tables)
How to select – or set a Range object – to the page that the cursor is on
Determine the index number of the current paragraph
Or of the current table, or section – or of any object that has a Range property
How to move a range variable to the end of an inserted file after using [range].InsertFile
Delete any paragraph that is an exact duplicate of the preceding paragraph, using a Range object
Delete any paragraph that is an exact duplicate of the preceding paragraph, using a Selection object
How to find out whether a range is off-screen
Working with Tables
Maximising the performance of Word tables
How can I resize a table to fit the page's width?
Deleting duplicate rows in a table
Deleting all empty rows in a table using a macro
Detect whether a table cell is empty
Delete all rows of a table that contain a particular text string in the first column
Determine the index number of the current paragraph, table, section ...
Or of any object that has a Range property
Apply changes to all cells in a table
Apply changes to an individual cell in a table
Select all but the first two cells in a table column
Display in a message box the contents of each cell in a table column
Select a range of cells within a table
Select all rows of a table except the first row
How to centre a left-justified table (or left or right-justify a centred one)
How to get the Rowspan and Colspan of a table cell using VBA
Change the behavior of the tab key inside a table cell
Turning “Allow spacing between cells” off with VBA in a Word 2000 table
Apply uniform table borders to all tables in a document
Working with strings, dates and Find & Replace
How do I return the date of the previous month using VBA?
How to Find & ReplaceAll on a batch of documents in the same folder
Flush bad karma from Word's find facility after an unsuccessful wildcard search
How to find out, using VBA, how many replacements Word made during a Find & Replace All
Or: How to find out how many occurrences there are of a particular word in a document
Detect when Word is trapped with a partial wildcard match at the very end of a document
Finding out how many times some text appears in a document
How to use Edit Find to select everything from where the cursor is to the first found item
How to replace text in quotation marks with italic or highlighted text minus the quotes
Change all dates in a document from MMMM DD, YYYY to DD MMMM YYYY
Replace one character with another wherever it appears in a string
Remove the underline attribute from characters with descenders
Apply the built-in Heading 1 paragraph style to all paragraphs containing text in ALL CAPS
Remove all empty paragraphs from a document
Working with menus and toolbars
How to get a true full screen view
Add a menu to the menu bar and populate it with commands
Add a toolbar button to launch an executable file
How to use VBA to set a custom graphic on a toolbar button
How to set the position on the screen of the toolbars and menu bars
Protect command bars against changes
Remove items from the Customize menu
How do I find out or change programmatically which macro is attached to a button on my toolbar?
How to create a menu to navigate to the non-hidden bookmarks in a document
Toolbar missing on add-ins tab in the Ribbon
Working with other objects and collections
How to convert the hyperlinks in a document to plain text
Or: How to prevent URLs from being converted to hyperlinks while I type
Manipulating the clipboard using VBA
How to clear the clipboard or get the text on the clipboard into a string variable
Size the text in a textbox to fill the textbox
Move shape anchors away from heading paragraphs
Scroll all open documents the same percentage as the active document
How to generate a table of samples of every font on your system
Let Clippy dance
How to display all the animations of the Office Assistant
Working with fields, forms & protected documents
Inserting nested fields using VBA
How to enable the spellchecker in a protected document
The best way to select a form field using VBA
How to set the "tab order" of a Word form
How to validate the contents of a formfield in a Word form
How to set the result of a text formfield using VBA, if the string is longer then 256 characters
How to assign a Name to a FormField that doesn't already have a Name, using VBA
Change Headers and Footers in a document protected for forms
Create a numbered list using SEQuence fields
Unlink all fields in the body of a document
Unlink all fields in the headers and footers of a document
How to hide a “Print” CommandButton on a document form when the user clicks on it
How to find the name of the current formfield
Update all fields in Word document
Add screen tips to text in Word
How to add small boxes with information that appear when you hover the mouse over over text in a document as known from links on websites.
Working with variables and arrays
Why variables should be declared properly
Create a module-level variable that can be used by any procedure (sub or function) within a module
When I sort an array it becomes filled with numbers instead of text
Using the Erase statement to clear an array
Working with files and directories
How to allow the user to browse to and select a folder
How to Find & ReplaceAll on a batch of documents in the same folder
Skipping Password-Protected Documents in a Batch Process
How to check if a file has already been opened by another user
How to copy an open file using VBA
How to create a copy of an open document
Insert into a document the names of all files in a selected folder
How to retrieve Word's default Documents path or Pictures path setting
How to delete files using VBA, including files which may be readonly
How to read the filenames
of all the files in a directory into an array
For instance, in order to populate a list box
How to get the names of all the folders in the folder tree, starting from a specified folder
How to ensure (using VBA) that all your Word add-ins are installed in the correct path
Extracting or exporting data from Word documents
Export or extract tracked changes
For a ready-to-use add-in that can extract acronymns, bookmarks, comments and tracked changes, see the free DocTools ExtractData add-in
Miscellaneous
How to do a mail merge to the printer using VBA, without displaying the Print dialog
Or in the case of Word 2002, how to do the opposite!
How to do a screen capture using VBA
Or: How to invoke the print screen command
How to get the username of the current user
Useful WordBasic commands that have no VBA equivalent
How to send an email from Word using VBA
How to get the most recently used document to be opened automatically when you open Word
Creating upside down or rotated text in Word
How can I tile documents vertically in Word 2000?
Find out whether Word was launched from its shortcut or by double-clicking a file
How to open a document invisibly to the user
How to activate a newly-created document
How to link a Word table with a Word graph
How to customize the Control Toolbox in the VBA Editor
So you don't have to set up all the properties for your controls every time you add one to a UserForm
“Invalid Page Fault” message when running a macro
Or: Combatting Template Bloat
Displaying WinHelp files from VBA
Creating sequentially numbered documents (such as invoices)
Sequentially numbering multiple copies of single document using a macro
How to remove manually typed numbering from a document
How to copy text and retain numbers when pasting elsewhere
How to speed up Word Automation by hiding the application
How to create list of local built-in style names
And a few “gotchas”How to make urls (and delimiters such as \, /, : and @) wordwrap in Word
Or: How to insert a zero-width space in your documents
Word commands, and their descriptions, default shortcuts and menu assignments
Create or edit AutoText via VBA
Errors and Bugs
“Invalid Page Fault” message when running a macro
Or: Keeping Word VBA projects “clean”
“Microsoft Forms: Could not load an object because it is not available on this machine”
“Undefined Variable” – Mid, Left, Right not working