PDA

View Full Version : Solved: Hiding Text and formfields using Styles



petedw
07-25-2005, 07:36 AM
Alright guys!

Got a form with the following macro. As you can see it searches for all text in the style "HiddenRed" and then hides it.
Well....that's not entirely true, it runs up to a certain point and then stops with the error "Object variable or With block variable not set"

It runs through a protected section of the document fine without having to do anything, then goes into a unprotected section and hides some text in there. Once that is done, it throws up the above error.
The only thing left for it to do is to hide a few formfields(in a protected area) in the "HiddenRed" style.

Sub WorkInProtectedDoc()

If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then ActiveDocument.Unprotect Password:=""

Dim par As Paragraph

For Each par In ActiveDocument.Paragraphs
If par.Range.Style = "HiddenRed" Then
par.Range.Font.Hidden = True
End If
Next par

ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True, Password:=""

End Sub

Cheers

Pete

MOS MASTER
07-25-2005, 10:57 AM
Hi Pete, :yes

By setting the para range to hidden you change the index of the paragraps collection and that's why you error out!

If you change a collection in your code you must always loop the collection backwards to front so you that you avoid those problems.

This will work:
Sub WorkInProtectedDoc()
Dim lPara As Long
With ActiveDocument
If .ProtectionType = wdAllowOnlyFormFields Then .Unprotect Password:=""

For lPara = .Paragraphs.Count To 1 Step -1
With .Paragraphs(lPara)
If .Range.Style = "hiddenred" Then
.Range.Font.Hidden = True
End If
End With
Next

.Protect Type:=wdAllowOnlyFormFields, NoReset:=True, Password:=""
End With
End Sub


HTH, :whistle:

fumei
07-25-2005, 07:11 PM
Ah, and not only that, but this kind of operation also changes the page numbers....just a note.

petedw
07-26-2005, 12:58 AM
Wahey!! :bow:

Once again i bow down to you Joost.
Thanks for the input Gerry. :thumb

Pete

MOS MASTER
07-26-2005, 09:44 AM
Wahey..right back at yah Pete! You're welcome! :yes