PDA

View Full Version : Cell Content



philipad
11-26-2008, 12:53 AM
Hi all

I use Microsoft 2003 Office and I am trying to use a code to copy the content of a cell and paste it into a bookmark. Instead of the cell content I get the cell itself copied into the bookmark.

Can anyone help?


Sub bookmarktest()

ActiveDocument.Tables(1).Cell(1, 1).Select
Selection.Copy
ActiveDocument.Bookmarks("book1").Select
Selection.Paste

End Sub

macropod
11-26-2008, 02:31 AM
Hi philipad,

Try something along the lines of:
Sub UpdateBook1()
Dim CellRange As Range
Dim BmkRng As Range
Dim BmkNm As String
BmkNm = "book1"
With ActiveDocument
Set CellRange = .Tables(1).Cell(1, 1).Range
CellRange.End = CellRange.End - 1
If .Bookmarks.Exists(BmkNm) Then
Set BmkRng = .Bookmarks(BmkNm).Range
BmkRng.Text = CellRange.Text
.Bookmarks.Add BmkNm, BmkRng
Else
MsgBox "Bookmark: " & BmkNm & " not found."
End If
End With
Set CellRange = Nothing
Set BmkRng = Nothing
End Sub
Note that this code simply replicates the text string - it doesn't copy any formatting. If you need to replicate the formatting, you could use something along the lines of:
Sub UpdateBook1()
Dim CellRange As Range
Dim BmkRng As Range
Dim BmkNm As String
BmkNm = "book1"
With ActiveDocument
Set CellRange = .Tables(1).Cell(1, 1).Range
CellRange.End = CellRange.End - 1
CellRange.Copy
If .Bookmarks.Exists(BmkNm) Then
Set BmkRng = .Bookmarks(BmkNm).Range
BmkRng.Paste
.Bookmarks.Add BmkNm, BmkRng
Else
MsgBox "Bookmark: " & BmkNm & " not found."
End If
End With
Set CellRange = Nothing
Set BmkRng = Nothing
End Sub
The reason the code is more complex than might at first seem necessary is that simply replicating or pasting the cell contents at the bookmark location results in whatever is replicated/pasted being inserted after the bookmark. Doing it as shown above means the replicated/pasted is kept within the bookmark - in case you want to change it again later.

A more generalised bookmark updating routine is:
Sub UpdateBookmark (BmkNm as string, NewTxt as string)
Dim BmkRng as Range
If Documents.Count > 0 then
If ActiveDocument.Bookmarks.Exists(BmkNm) Then
Set BmkRng = ActiveDocument.Bookmarks(BmkNm).Range
BmkRng.Text = NewTxt
ActiveDocument.Bookmarks.Add BmkNm, BmkRng
End if
End if
Set BmkRng = Nothing
End sub
With this code, you'd pass both the bookmark name and its new contents to the sub.