View Full Version : Word VBA find and replace field code in Table Caption
mehunter
11-18-2019, 05:24 PM
Looking for the Word vba code to find "{ SEQ Table \* ARABIC }" and replace with "{ STYLEREF 1\s } - { SEQ Table \* ARABIC }"
Not sure if this is possible.
Thanks
Mavila
11-18-2019, 06:23 PM
I have a procedure where I loop through Sections, many of which have a TOC fields using bookmarks.  I identify the TOC Field code, and then isolate the bookmark name for further use.  Maybe this will give you an idea how to go about it.
    ActiveWindow.View.ShowFieldCodes = True 'Show the Field Code so you can work with the contents
        For Each myFld In myRange.Fields 'Loop through each field in the Active Document
            If myFld.Code Like "* TOC \f \b *" Then 'It's a TOC Field. Field Code Format = { TOC \f \b hazcom \z }
                myFld.Select
                'Isolate the Field's identifier/name which matches the bookmark's name. Field Code Format = { TOC \f \b hazcom \z }
                y = 0
                x = InStr(1, Selection, "\b ")
                x = x + 3
                Do Until fldNm Like "* \z*"
                    fldNm = Mid(Selection, x, y)
                    y = y + 1
                    If y >= 100 Then ‘Protects against runaway loops
                        Stop
                    End If
                Loop
                fldNm = Mid(Selection, x, y - 4) 'This should be the Field's identifier/name that matches the bookmark's name
                'Use the Start and End Bookmarks (placeholders without text at the start/end of the chapter) to make a new bookmark that contains
                'the entire text of the chapter which is necessary for the TOC to work (it references all TC fields in the bookmark)
                ActiveDocument.Bookmarks.Add Name:=fldNm, Range:=Selection.Sections(1).Range 'Bookmark contains all contents of the Chapter/Section
                myFld.Update 'Update the TOC and then apply formatting to make sure it looks proper
                Selection.Font.Bold = False
                Selection.Font.Underline = wdUnderlineNone
                Selection.Font.Name = "Times New Roman"
                Selection.Font.Size = 12
                Selection.ParagraphFormat.SpaceAfter = 0
                Exit For 'Exit loop and go on to the next section
            End If
        Next
Mavila
11-18-2019, 06:54 PM
Do something like this to create a field:
        strFldTxt = "TC  """ & ChptrNm & """ \b " & TOC_Chptr & " \l 1"
        oRange.Fields.Add Range:=oRange, Type:=wdFieldEmpty, Text:=strFldTxt, PreserveFormatting:=False
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.