unable to search for style

C

Chip Orange

Hi All,

I'm having a problem with the following code failing to find something which
is in the document. I know it's there because I can type similar code into
the immediate window and have it work (also below).

Fails:

DIM objRange as Word.Range


SET objRange = ActiveDocument.range
WITH objRange.Find
.ClearFormatting
.Text = "Issue"
.Style = ActiveDocument.Styles("Issue Heading")
END WITH

IF objRange.Find.execute() then
....



and it fails. If I type this into the immediate window, using the selection
object like so:

selection.find.ClearFormatting
selection.find.Text = "Issue"
selection.find.Style = ActiveDocument.Styles("Issue Heading")
? selection.find.execute()


and that works! :( ?

I don't want to use the selection object in my macro for other reasons, and
this is a paired-down example so maybe I left something key out, but I don't
see any essential difference. If I don't use style, but I use attributes
such as bold and underlining, then the first search example works ok, it's
only when searching for text in a specific style that it fails.

Any ideas?

Thanks.

Chip
 
J

Jay Freedman

Range objects and the Selection object behave differently with respect to
the "stickyness" of the parameters. A newly created Range object's .Find
parameters are all the defaults, while the Selection.Find inherits most of
its parameters from the most recent search that used the Selection
(including one done through the Edit > Find dialog).

In your code, include .Format = True to make it use the .Style parameter
instead of ignoring it. I'll guess that when you tried the Selection search
in the Immediate window, it inherited the .Format value from a previous
search using the dialog.

That said, I would have expected the Range search as you showed it to find
the word "Issue" in any text, regardless of its style -- that is, you might
get hits you don't want, rather than not getting hits you do want. Maybe
there's something else going on.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top