December 21, 2010 8:16 PM Subscribe
VBA for Word help. A lot of help. I'm trying to find a string, then search and replace a space within that string. I can do parts of this, but not the whole thing and not for the whole document at once.
posted by theredpen to Technology (13 answers total)
So I'm lazy. I like to automate certain Word tasks. I've been doing this with a few wildcard searches in Word, but wouldn't it be nice for me to have a script rather than having to type the search each time? It would!
Here's an example. I want to replace all instances of "X. Y." with "X.Y." (closed up space), for example. Manually, I can search for all instances of "X. Y." in the main document with Find > with wildcards > [A-Z]\. [A-Z]\.". Then I do a search and replace for " " (a space) with "" (nothing) within that selection.
I can't figure out enough VBA for Word to get this done automatically. I had it apparently working for a single instance, but I had to run the macro over and over again rather than it looping through the document.
.Text = "[A-Z]\. [A-Z]\."
.MatchWildcards = True
.Wrap = wdFindStop
Do While .Found = True
.MatchWildcards = False
.Text = " "
.Replacement.Text = ""
(And once that worked and then it seemed to not work.) I don't know what Word's problem is, but I just can't find the right VBA code for this one thing I want to do. If I get this working, I can modify it for other searches. Asking too much? Doomed to search manually forever? I'm in over my head, obviously.