PDA

View Full Version : [SOLVED:] Finding a built-in heading



Roderick
11-16-2018, 09:43 AM
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

gmayor
11-16-2018, 09:07 PM
has been inserted somewhere up the pageVBA 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.

macropod
11-16-2018, 11:14 PM
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

Roderick
11-19-2018, 04:22 AM
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