StyleRef in VBA

J

John Marshall, MVP

Is there any way of getting the content of a style that precedes the current
selection? It is possible to use StyleRef to add the information to the
document and then read the content of the header, but this may not be
practical.

John... Visio MVP
 
L

Lene Fredborg

I may not understand your description correctly. If you by "content of a
style" mean that you want to get the content of the _paragraph_ immediately
before the first paragraph in the current selection, something like the
following may do what you want:

Dim strText As String

With ActiveDocument
'Only find text if first paragraph in document
'is not included in the selection
If .Paragraphs(1).Range.InRange(Selection.Range) = False Then
'Get content from the paragraph preceding the first paragraph in
the selection
strText = .Paragraphs(.Range(0,
Selection.Paragraphs(1).Range.End).Paragraphs.Count - 1).Range.Text
End If
End With

If tables are involved, you may need to make adjustments to the code.

--
Regards
Lene Fredborg
DocTools - Denmark
www.thedoctools.com
Document automation - add-ins, macros and templates for Microsoft Word
 
J

John Marshall, MVP

Not quite.

I'm looking for the content of style that precedes the selection pointer,
but it may be several paragraphs (or pages) back.

For example the document contains a header2 style with a value of
"background discussion". Some where after this paragraph, maybe several
paragraphs later is the word "John". The insertion point is at "John" and I
would like to add the text "John" and "background discusssion" to a message.
The string "John" I can obtain, I just can not think of an easy way of
finding "background discussion". I could insert a StyleRef at the selection
pointer, grab the text and delete the styleref, but I would prefer not to
mess with the document.

John... Visio MVP
 
L

Lene Fredborg

OK - hopefully I understand the problem better now. Maybe you can use
something like the code below. It uses Find (without changing the selection)
to retrieve the text from the first preceding paragraph with the style
Heading 2:

Dim strText As String
Dim oRange As Range

'Only search text above the selection
Set oRange = ActiveDocument.Range(0, Selection.Range.Start)
With oRange.Find
.Style = wdStyleHeading2
.Wrap = wdFindStop
'Search up
.Forward = False
.Execute
If .Found = True Then
strText = oRange.Text
Else
MsgBox "No text found with style Heading 2 before the selection."
End If
End With

Set oRange = Nothing

--
Regards
Lene Fredborg
DocTools - Denmark
www.thedoctools.com
Document automation - add-ins, macros and templates for Microsoft Word
 
J

John Marshall, MVP

Thanks Lene, looks like there is not a simple solution.

John... Visio MVP
 

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

Top