vbafor-loopms-word

Problem with cycling through Styles to change NextParagraphStyle - Run time error 91 - Word vba


Problem with cycling through Styles to change NextParagraphStyle - Run time error 91 - Word vba

EDIT: Tim Williams spotted the problem. I was not using Set for an object variable.

My macro is:

Sub StyleFollowingBodyText()
    ' Charles Kenyon 15 December 2024
    ' Set the following style for most QuickStyle paragraph styles to be Body Text
    Dim StyleCount As Long
    Dim thisStyle As Style
    Dim iCount As Long
    '
    With ActiveDocument
        Let StyleCount = .Styles.Count
        For iCount = 1 To StyleCount
            Let thisStyle = .Styles(iCount)
            If thisStyle.QuickStyle = True Then
                If thisStyle.Type = wdStyleTypeParagraph Or wdStyleTypeLinked Then
                    If thisStyle.NameLocal <> "Normal" Then
                        thisStyle.NextParagraphStyle = "Body Text"
                    End If
                End If
            End If
        Next iCount
    End With
End Sub

and I get this error message when running it:

screenshot of error 91

This error message seems to be somewhat of a "catch-all" and is not that helpful. As pointed out by Tim Williams, the problem is not using the Set command for an object variable.

It is stopping on Let thisStyle = .Styles(iCount).

The purpose of the macro is to change most of the paragraph QuickStyles to have the Body Text style as the following style. I am trying to change more than 50 [Quick] Style Sets because I prefer to not have the bulk of my documents using the Normal style.


Solution

  • For example:

    Sub StyleFollowingBodyText()
    Dim s As Long
    With ActiveDocument
      For s = 1 To .Styles.Count
        With .Styles(s)
          If .QuickStyle = True Then
            If .NameLocal <> "Normal" Then
              If .Type = wdStyleTypeParagraph Or .Type = wdStyleTypeParagraph Then .NextParagraphStyle = "Body Text"
            End If
          End If
        End With
      Next
    End With
    End Sub