VBA function to look for styles

J

jose_piratilla

This question was posted on the word general questions discussion, but I
think that it can fit better on this discussion.

I need a function to check if some style is present in a determined page. I
will use that function in the header to decide when to show it with a field
like this:
{ IF IsStylePresent{ PAGE } " " "Bla Bla Bla" }

I have experience with VBA in Access, but no idea about word document
object. Any help?
 
G

Graham Mayor

Investigate the Styleref field.

--
<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
Graham Mayor - Word MVP


<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
 
J

jose_piratilla

I've investigated it, but I can't find the way to get the information I want.
The styleref gives me the paragraph with this style nearest to the page I'm
in. But it don't says me if the match is in the current page or in another.
So I can't deduce if a style is present in a page or not.
 
S

StevenM

: << I need a function to check if some style is
present in a determined page. >>

One problem you’ll face is that while VBA has collections for sections,
paragraphs, sentences, words, and characters, it doesn’t have a collection
for pages. My guess would be that a page doesn’t fit into a logical
hierarchy, since sections, paragraphs, sentences, and even words, can break
across pages. Nonetheless, I think I’ve come up with something which works.
Obviously, you will need to substitute “Bob†for whatever style you’re
looking for.

Steven Craig Miller

Sub FindPageOfStyle()
Dim actDoc As Document
Dim oStyle As Style

Set actDoc = ActiveDocument
Set oStyle = actDoc.Styles("Bob")
MsgBox PageOfStyle(actDoc, oStyle)

End Sub

' I don't normally use the selection object and
' so there might be a better way to set oSel.
' The reason for using it here is that if the Find
' object comes from a Selection object, then the found
' text is selected. And that is needed to find the
' page number.

Function PageOfStyle(ByVal oDoc As Document, oStyle As Style) As Long
Dim oSel As Selection
Dim nPage As Long

oDoc.Select
Set oSel = Selection

oSel.Collapse Direction:=wdCollapseStart
With oSel.Find
.ClearFormatting
.Style = oStyle
.Forward = True
.Format = True
.Text = ""
.Execute
If .Found = True Then
nPage = Selection.Information(wdActiveEndPageNumber)
Else
nPage = 0
End If
End With
PageOfStyle = nPage
End Function
 
J

jose_piratilla

Thanks, it is not exactly what i was looking for, but it shows me how to do
it. Thanks a lot.
 

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