Search code examples
ms-wordbookmarks

how to create bookmarks within table


I am automating the word document processing where I add bookmarks based on a search criteria. The code works great but it fails when I have tables in the document. It seems like in the normal document when I read the text it is given as line per line but in case of tables the text has columns and rows. So, when I seach a text and that text is written in two lines in a single column the result would be ok but when I select the text WORD API selects the text from two columns instead of the same column but two lines.

col1          col2
This is       Second Column
Some Text

Now if I search the text "This is Some text" I got it correctly but when I select it I got "This is Second Column"

reg = New Regex(result.token(j).ToString())
                Dim m As Match = reg.Match(_doc.Range.Text, 0)
                pos = m.Index ' start position is fine

                ''  start is the starting position of the token in the content...
                ''length is the size of the token
                len = result.token(j).ToString().Length ' text length is fine

                rng = _doc.Range(pos, len + pos) ' this copies the text from the second col
                _doc.Bookmarks.Add(bookmarkName, rng)

Solution

  • instead of selecting the text by length, you can select the whole cell, try to adapt your code this way:

    rng = Selection.Cells(1).Range