What to Think About When Writing a Macro
Recently on the Microsoft Community Forum a Microsoft 365 Word user asked for help creating a macro that would find all pictures they had in a document and put each picture into a separate document along with the picture’s caption. They also wanted to name each new document the caption name label. For example, a picture with the caption label of “Figure 1” would be copied into a new Word document and the new document’s filename would become “Figure 1.docx.”
Taking a critical look at the requirements for this macro, a few questions arise.
Is the caption above or below each image?
Does the macro search for pictures or captions?
Are the pictures placed inline on their own paragraph or is there wrapping text around them?
If using the Caption text for the resultant filename, what happens if there are special characters in the Caption that Windows does not allow in filenames?
If only the Caption label and number are used for the filename, what happens when the macro tries to save the new file and there already exists a file called Figure #?
Whenever you create a macro that will automate repetitive tasks, you have to think about various possible scenarios that may arise and either allow for them in the macro’s code or define the source data requirements … in this case, what are we expecting to find in the source document’s formatting, and if the unexpected happens, how do we handle it?
VBA CODE to Find and Move Pictures and Captions from One Document to Others
The following is the VBA code I wrote that performs the task the Microsoft 365 Word user requested. Interspersed throughout the code are comments that explain what is being done and why. In other words, based on those five questions I shared above, I am showing you my thought process and logic. Comments in VBA code all begin with a single quote mark, and I’ve colored the comment text green. Please note that the text strings in double quotation marks are also showing as green, but anything in double quotation marks are part of the code (not comments.)
To sum up
Whenever you create a macro to automate repetitive tasks:
Consider the possible scenarios that may arise.
Allow for them in the macro’s code.
Or define the source data requirements … and if the unexpected happens, how is that handled?