Results 1 to 3 of 3
  1. #1
    New Lounger
    Join Date
    Feb 2015
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thumbs up Run-time error 91 - VBA Macro for inserting and formatting text depending on style

    Hello!

    I've been having some trouble with the following code:

    Code:
    Sub AutomaticNumbering()
    Dim manum As Field
    Dim rgpara As Paragraph
    Dim myRange As Range
    Dim notag As Range

    For Each rgpara In ActiveDocument.Paragraphs

    If rgpara.Range.Style = "Text" Then
    Set myRange = rgpara.Range
    Set notag = myRange.Next(Unit:=wdParagraph, Count:=1)


    If notag.Style = "MNS" Then

    Else

    rgpara.Range.InsertParagraphAfter
    myRange.Collapse Direction:=wdCollapseEnd
    myRange.Style = "MNS"
    Set manum = ActiveDocument.Fields.Add(Range:=myRange, Type:=wdFieldAutoNumLegal, Text:="\Arabic *\e", PreserveFormatting:=True)
    End If

    End If

    Set notag = Nothing
    Set myRange = Nothing
    Set manum = Nothing
    Set rgpara = Nothing

    Next rgpara



    End Sub

    The function works fine, but in the end I get "Run-time error 91 Object Variable or With block variable not set".

    The Debug indicates the problem might be related to the following line:

    Code:
    If notag.Style = "MNS" Then

    Does anyone have an idea to help?

  2. #2
    Super Moderator
    Join Date
    Jan 2001
    Location
    Melbourne, Victoria, Australia
    Posts
    3,852
    Thanks
    4
    Thanked 259 Times in 239 Posts
    The code is failing because when you get to the last paragraph in the document there is no next paragraph.

    You could modify the if statement along the lines of
    If notag is nothing then
    'do something
    elseif notag.style = "MNS"
    'do something else
    end if
    Andrew Lockton, Chrysalis Design, Melbourne Australia

  3. #3
    Super Moderator
    Join Date
    May 2002
    Location
    Canberra, Australian Capital Territory, Australia
    Posts
    5,054
    Thanks
    2
    Thanked 417 Times in 346 Posts
    Cross-posted at: http://www.msofficeforums.com/word-v...inserting.html
    For cross-posting etiquette, please read: http://www.excelguru.ca/content.php?184
    Cheers,

    Paul Edstein
    [MS MVP - Word]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •