Word 2000: How to Insert a Table in a Bookmark with VBA

V

VBA Coder

Does anyone know how I can insert a Table in a Bookmark using VBA?

I have the following code that inserts a table at the bookmark, however,
each time I run my Macro to insert the table, I get a new table placed
inside the 1st table's first cell. I need the bookmark to be cleared out
(ie: Table removed) each and every time I run my Macro.

Dim rRange As Range, myTable As Table

ActiveDocument.Bookmarks("TableBookmark").Select
Selection.Collapse Direction:=wdCollapseStart
Set myTable = ActiveDocument.Tables.Add(Range:=Selection.Range, _
NumRows:=6, NumColumns:=3)
myTable.AutoFormat Format:=wdTableFormatClassic2
 
J

Jay Freedman

VBA Coder said:
Does anyone know how I can insert a Table in a Bookmark using VBA?

I have the following code that inserts a table at the bookmark, however,
each time I run my Macro to insert the table, I get a new table placed
inside the 1st table's first cell. I need the bookmark to be cleared out
(ie: Table removed) each and every time I run my Macro.

Dim rRange As Range, myTable As Table

ActiveDocument.Bookmarks("TableBookmark").Select
Selection.Collapse Direction:=wdCollapseStart
Set myTable = ActiveDocument.Tables.Add(Range:=Selection.Range, _
NumRows:=6, NumColumns:=3)
myTable.AutoFormat Format:=wdTableFormatClassic2

You have two problems here: (1) you aren't doing anything to remove
the old table if it exists, and (2) when you insert something in a
bookmark, it overwrites the bookmark so it no longer exists. The code
needs to be a good bit smarter to do what you want...

Public Sub TableInBookmark()
Dim rRange As Range, myTable As Table
Dim BkMkName As String

BkMkName = "TableBookmark"

' make sure the bookmark exists
If Not ActiveDocument.Bookmarks.Exists(BkMkName) Then
MsgBox prompt:="Bookmark '" & BkMkName & _
"' not found", Title:="Error"
Exit Sub
End If

' get its range
Set rRange = ActiveDocument.Bookmarks(BkMkName).Range

With rRange
' remove any existing table in bookmark
If .Tables.Count > 0 Then
.Tables(1).Delete
End If

' add new table
Set myTable = .Tables.Add(Range:=rRange, _
NumRows:=6, NumColumns:=3)
myTable.AutoFormat Format:=wdTableFormatClassic2

' inserting the table kills the bookmark;
' reconstruct it so the macro won't fail
' the next time it runs
ActiveDocument.Bookmarks.Add Name:=BkMkName, _
Range:=myTable.Range
End With
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top