[Word]Active Document Styles and IfThen Statements
So when the document contains the Style "Side Head", this code obviously works fine. But if the document doesn't contain it, it seems to ignore the Else If part of the statement and return an error that states:
Run-time error '5941':
The requested member of the collection does not exist.
When I select Debug, it highlights the line "Selection.Find.Style = ActiveDocument.Styles("Side Head")
So how can I write this so that it will actually use the If Then statement?
Thanks.
Code:
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Side Head")
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchByte = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchFuzzy = False
End With
Selection.Find.Execute
If Selection.Find.Found = True Then
Selection.HomeKey Unit:=wdLine
Selection.TypeText Text:="TEST"
Else
End If
Re: [Word]Active Document Styles and IfThen Statements
It is not working because the error is happening when trying to access a member that does not exist, so the IF-Then statement is never reached. If what you want to do is verify that the style exist, then loop through the collection and search for the name
vb Code:
Dim found As Boolean
Dim myStyle As Style
found = False
For Each myStyle In ActiveDocument.Styles
If myStyle.NameLocal = "Side Head" Then found = True
Next myStyle
Re: [Word]Active Document Styles and IfThen Statements
I don't simply want to verify that the style exists, I want to find the style, then if it exists, I want to move to the front of it and insert the text "Test". Then do that until all the similar style has been found.
If the style is not found in the document, then I simply want it to move on.
Re: [Word]Active Document Styles and IfThen Statements
THat code will thell you if the style exist, if it does you can do all that you wanted to do, but if it does not, then don't go into the .Find as your code will throw an error. Just do that with the found boolean variable or adjust the code as you wish.