Problem with macro searching for overlapping strings and inserting a comment
Hi all, I'd be grateful for your help on a Word macro problem that I'm facing. I'm not a VBA programmer (just an ordinary Word user) and so I don’t know all the tips and tricks for writing macros: I'd really appreciate your experience here.
I'm writing macros that search for all occurrences of a string, and then include a comment bubble on that string. The problem I've realised is that Word search does not appear to work properly if a string already has an existing comment marked on part of that string.
For example, imagine (using random search terms):
1. (First string) I search in a document for all occurrences of the string "without," and apply a comment to each of those (e.g. "This is string: without").
2. (Second, overlapping, string) I then search in a document for all occurrences of the string "without you," and try to apply a comment to each of those (e.g. "This is string: without you").
Step 2 does not work. The find functionality in Word can't seem to identify "without you" in step 2 where "without" already has a comment applied to it from step 1.
I tried to solve for this by changing comments to footnotes, but I get the same problem: if you have a footnote applied after "without" in step 1, Word search cannot find "without you" in step 2.
I thought wildcards would solve this, but they don't: e.g. the search term "without*you" does not identify either "without you" already marked with a comment, or "without1 you" where a footnote has been applied to "without" previously.
If it helps, here is the (clunky and inefficient I'm sure) macro code I've been using:
Sub CallMacros()
Call 001Without
Call 002WithoutYou
End Sub
Sub 001Without()
Dim range As range
Set range = ActiveDocument.Content
Do While range.Find.Execute("without", False) = True
ActiveDocument.Comments.Add range, "This is string: without"
Loop
End Sub
Sub 002WithoutYou()
Dim range As range
Set range = ActiveDocument.Content
Do While range.Find.Execute("without you", False) = True
ActiveDocument.Comments.Add range, "This is string: without you"
Loop
End Sub
The only solution I've found is a manual workaround: to change the call order so that larger strings are called before shorter ones (e.g. here, calling 002WithoutYou before 001Without). But it seems wrong to use this manual workaround: it relies on getting the call order right, which seems inefficient.
It looks like LibreOffice doesn't have this search issue (e.g. even if a comment is applied to "without", a search will find "without you"), but I don't know how to code macros in LibreOffice and so would prefer not to switch processors.
If there's a much better way of doing this, I'd really appreciate hearing about it, thank you all!!
|