Consulting

Results 1 to 4 of 4

Thread: Finding a built-in heading

  1. #1

    Finding a built-in heading

    In this case, I'm using Windows 10 and Office 365.

    Here's the problem and I don't know where to start. I can only explain as I cannot think of any suitable code to write.

    I've got a document based on a template and using the built-in Heading 1 to 6, in this case.

    Heading 1 has a number formatting of 1.0; Heading 2 has a formatting of 1.1; Heading 3 a formatting of 1.1.1 and so on down to level 6.

    I now want to put in a table with a caption after, say, a Heading 3 (1.1.1) has been inserted somewhere up the page. What I want Word VBA to do is run up the page until it discovers what Heading it meets, remember what level it is, then run back down where the table caption is going to go and format the {STYLEREF} field to indicate that it is a Heading 3.

    As I include Chapter numbering when Inserting Caption using Heading 3 I get Table 1.1.1-1 (if its the first table after Heading 3). And so on.

    I can achieve this manually by editing the STYLEREF field but that is as far as I can go. It needs to be done via VBA.

    Can anyone point me in the right direction, please?

    Thanks

    Roderick

  2. #2
    has been inserted somewhere up the page
    VBA doesn't do vague. Is this the last heading style on the page or are there other heading styles on the page. The macro needs some reference point to work with.
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

  3. #3
    Knowledge Base Approver VBAX Guru macropod's Avatar
    Joined
    Jul 2008
    Posts
    4,435
    Location
    Try something based on:
    Sub Demo()
    Dim Rng As Range, Lvl As Long
    With Selection
      Set Rng = .Range
      Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
      Lvl = Right(Rng.Paragraphs.First.Style, 1)
      .Fields.Add Range:=.Range, Type:=wdFieldEmpty, Text:="StyleRef ""Heading " & Lvl & """ \n", PreserveFormatting:=False
    End With
    End Sub
    Cheers
    Paul Edstein
    [Fmr MS MVP - Word]

  4. #4
    Thanks, Paul.

    You helped solve the riddle!

    This was the code that I didn't know and fixed what I needed.

    Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
    Thanks, again.

    Roderick

Posting Permissions

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