Hi all,
I am writing a macro in MS Word which should find all highlighted text in a document and perform some action on each. I am planning a loop to do the search and manipulation part and have no problem with this portion of the code.
But I don't know how to find how many iterations I'm going to need. Is there a way to determine the number of highlights in VBA?
Many thanks in advance.
views:
30answers:
1
+2
A:
With ActiveDocument.Range.Find
.Highlight = True
While .Execute
Debug.Print .Parent.Text
Wend
End With
There's no need to calculate the number of matches up-front. You can execute the search in a loop and it will stop once there are no more matches.
Make sure you apply the search to the right part of the document.I used ActiveDocument.Range
, but any Range
object will do. Maybe something more specific is better for your case.
Also, check out the many other properties of the Find
object and set them to sensible values, this is better than going with the defaults (nobody can remember all defaults for all options, plus the Find
object might already be set up by some earlier search).
Tomalak
2010-04-20 18:42:10
Thank you man. It works like a marvel. But if it is not asking for too much, could you also hint if the number can be found at all? You see, before entering the loop the macro performs other edits and it will be a good feature to check if the document has already been processed or not, so if a user invokes the macro twice, it detects that it's been executed once and exits. This will work if I can find the number of highlights because the macro removes highlight mark from chunks and after it's done there are none left.
Majid
2010-04-20 19:43:59
@Majid: If there are no highlights left after the first pass then the loop would not even run on the second try, well, because there are no highlights left (i.e., `Execute()` returns `False` right away). ;) Or maybe I don't understand exactly what you want?
Tomalak
2010-04-20 21:03:47
@Tomalak: Yes the code inside the loop would not run on the second execution, but I have code before the the loop, which will execute. That is why I need a check if there are any highlights in the document at all. I would conduct this check as the first thing the macro does. If there is no way to access this number directly, I guess, I'd need two nested while loops?
Majid
2010-04-21 09:29:19
@Majid: You are too fixed on the number, but the number is not really important for what you want to do. You want to know if there are *any* highlights at all, not how many. Just `Execute()` the search once (at the start of your macro). It will return True or False. True means, there is at least one highlight, False means your're done.
Tomalak
2010-04-21 10:09:47