简体   繁体   中英

Word VBA to Delete Tables with Bookmarks

I have a Word Document with multiple Tables. Some of them have bookmarks and the other don't. Is there a way to implement ConvertToText command ONLY on the tables with the bookmarks on them using VBA (regardless of the bookmark name....I have over 40 bookmarks)? Basically, I'm trying to get rid of the bookmarked tables and keep just the text in those. The bookmarked tables are inserted INSIDE other tables WITHOUT bookmarks. I'm using MS Word 2007.

Thanks in Advance! Seb

Yes, there is quite simple solution. You need to loop through all bookmarks and check if one is wdWithInTable . If so, convert whole table into text. Here is a code for you:

Sub ConvertTablesWithBookmarks()


    Dim BK As Bookmark
    For Each BK In ActiveDocument.Bookmarks
        If BK.Range.Information(wdWithInTable) Then
            'uncomment for test just to check if working as expected
            'BK.Range.Tables(1).Select

            BK.Range.Tables(1).ConvertToText
        End If
    Next

End Sub

After additional explanation in comment below there are some hints for you to solve your problem.

To find a table in which your bookmark is:

Activedocument.bookmarks(1).Range.Tables(1)

To find first table in above table you use this code

Activedocument.bookmarks(1).Range.Tables(1).Tables(1)

but I think you can have a few tables inside you parent table. Therefore i suggest to run a loop like this (pseudo code, requires some adjustment to your needs):

dim parentTable as Table
dim BK as Bookmark     'or a reference to one from loop above
set BK = Activedocument.bookmarks(1)
set parentTable = BK.Range.Tables(1)
dim i as integer
for i=1 to parentTable.Tables.Count
    if parenttable.tables(i).range.start >=bk.range.start and _
       parenttable.tables(i).range.end <=bk.range.end Then
       'here we know that tables(i) is inside bookmark 1 (BK)

       parenttable.tables(i).converttotext
     end if
next i

I didn't have an oportunity to test it but hope it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM