PDA

View Full Version : Populating Bookmarks From Word Table



Jfp87
04-02-2015, 04:27 AM
Guys,

Looking for a bit of help populating bookmarks with data taken from multiple word tables (all word tables are contained within the same document).

Each word table will have 2 columns; column 1 is a list of bookmark names and column 2 is a list of generic statements.

The code will search through the document for every occurance of a bookmark. It will then check the bookmark name, and compare it to the table names to determine which table the applicable data is in. It will then select the relevant generic statement in the table using the bookmark name (i.e. bk_Table1_1 would select the 1st generic statement in column 2).

I have included one small table and some code below....I am getting confused by my loops. I also don't understand why in my code, if i set a for loop "for i = 0 to 2", then watch "i" in the watch window, the value of "i" can become 3...?

I know the following code is incorrect...but will help you see my train of thought.

Dim arrTable() As String
Dim oRng As Word.Range
Dim bk As Bookmark
Dim i As Integer
Dim j As Integer
arrTable = Split("Height|RATs|Scaff|", "|")
For Each bk In ActiveDocument.Bookmarks
Set oRng = bk.Range
For i = 0 To UBound(arrTable)
If InStr(1, bk.Name, arrTable(i)) > 0 Then
For j = 1 To ((ActiveDocument.Tables(i + 1).Rows.Count) - 1)
If bk.Name = "bk_" & arrTable(i) & "_" & j Then

bk.Range.Text = ActiveDocument.Tables(i + 1).Rows(j + 1).Cells(2).Range.Text
'ActiveDocument.Bookmarks.Add "bk_" & arrTable(i) & "_" & j, oRng
GoTo Continue

End If
Else

Next i

End If

Next j

Continue:
Next bk
End Sub




Bookmark Name

Statement



bk_Height_1

Statement 1



bk_Height_2

Statement 2

gmayor
04-03-2015, 05:18 AM
It is difficult to understand the logic of what you are attempting, or the relationship between the array and the tables. If all you want to do is fill some bookmarks from those listed in tables in the document, then provided the tables have the bookmark names in Column 1 and the values in Column 2 (other columns are ignored) then the following will do that. The macro doesn't care whether there is a header row, nor whether some of the named bookmarks are missing. It will populate those it matches.



Option Explicit

Sub BookmarksFromTables()
Dim oTable As Table
Dim oCell As Range, oValue As Range
Dim i As Integer
For Each oTable In ActiveDocument.Tables
For i = 1 To oTable.Rows.Count
Set oCell = oTable.Cell(i, 1).Range
oCell.End = oCell.End - 1
Set oValue = oTable.Cell(i, 2).Range
oValue.End = oValue.End - 1
FillBM oCell.Text, oValue.Text
Next i
Next oTable
lbl_Exit:
Exit Sub
End Sub

Private Sub FillBM(strBMName As String, strValue As String)
Dim oRng As Range
With ActiveDocument
On Error GoTo lbl_Exit
Set oRng = .Bookmarks(strBMName).Range
oRng.Text = strValue
oRng.Bookmarks.Add strBMName
End With
lbl_Exit:
Exit Sub
End Sub