How to Find and Replace in a Word document using VBA?
How to Find and Replace in a Word document using VBA?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
19-Jul-2023Sure, here is the code to find and replace in a Word document using VBA:
This code first declares a few variables:
doc
is a variable of typeWord.Document
that represents the active document.findWhat
is a variable of typeString
that contains the text you want to find.replaceWith
is a variable of typeString
that contains the text you want to replace the find what text with.startAt
is a variable of typeInteger
that contains the location in the document where you want to start the search.found
is a variable of typeBoolean
that indicates whether or not the find what text was found.The code then gets the active document using the
ActiveDocument
property. It then gets the find what text from the user using theInputBox
function. It then gets the replace with text from the user using theInputBox
function. It then gets the start at location from the user using theInputBox
function.The code then sets the
found
flag to false. It then loops through all the words in the document. For each word, the code checks if the word's text matches the find what text. If it does, the code sets thefound
flag to true and replaces the word with the replace with text.If the find what text was not found, the code displays an error message.
To use this code, you would first need to insert it into a new or existing Word VBA project. You would then need to run the code. When running the code, you would be prompted to enter the find what text, the replace with text, and the start at location. Once you have entered all of the information, the code will find and replace the text in the document.