
Tips.Net > WordTips Home > Macros > Creating Macros > Repeating in a VBA Macro
Summary: How to loop through a complete document in your VBA macro. (This tip works with Microsoft Word 97, Word 2000, Word 2002, and Word 2003.)
One of the most common things you need to do when creating a macro is to repeat a block of actions for each occurrence of something within a file. This may sound strange, but those who program know the situation very well--you need to search through a file and then take some action, repeat the search and repeat the action, and so on until the end of the file is reached. The general approach is as follows:
Selection.HomeKey Unit:=wdStory
[set up for your search]
Selection.Find.Execute
While Selection.Find.Found
[take some action]
Selection.Find.Execute
Wend
The first line in this example moves to the beginning of the document. You then use whatever commands necessary to set up for your search. When the Selection.Find.Execute line is encountered, Word performs the actual search. Then Selection.Find.Found is used to control the While ... Wend loop. This property (Selection.Find.Found) is set to True each time an executed search actually results in something being found. Thus, the whole While ... Wend loop is repeated over and over again, as long as whatever you are searching for continues to be found. As the last step in the loop, the Selection.Find.Execute statement is used to once again perform the search.
Tip #1083 applies to Microsoft Word versions: 97 2000 2002 2003
Ultimate Library! An amazing resource that brings together, in one place, the collected knowledge of everything ever published in WordTips. The library combines two powerful elements to make you more productive: solutions and convenience. Here's where you get your own copy of everything ever published in WordTips.
Check out WordTips Ten-Year Library today!
The real power behind Word's best documents lies in understanding styles and templates. Learn the key to more powerful document creation. (more information...)
Ask a Word Question
Make a Comment
Beauty Tips
Car Tips
Cleaning Tips
College Tips
Cooking Tips
Excel2007 Tips
ExcelTips
Family Tips
Gardening Tips
Health Tips
Home Tips
Money Tips
Organizing Tips
Pest Tips
Pet Tips
Word2007 Tips
WordTips