PDA

View Full Version : Pasting cells in an existing table



bigjaker
02-11-2009, 02:18 PM
I have a table that I go to in another document (document2) and select a range of cells, then they are copied and the active document is closed. Next I go to a spot in another open word document, in a table that is the same size.

The problem I am having is that I can't get the paste to work correctly. I need basically a "paste cells" I use it in the edit menu all of the time, but how to I make it work in VBA?

Below is a small snippet of my vba I am using and problem is at the bottom.


Selection.MoveDown Unit:=wdLine, Count:=2
Selection.MoveRight Unit:=wdCell, Count:=3
Selection.MoveDown Unit:=wdLine, Count:=24, Extend:=wdExtend
Selection.Copy
ActiveWindow.Close 'closes document2
Selection.GoTo What:=wdGoToTable, Which:=wdGoToFirst, Count:=3, Name:=""
Selection.Find.ClearFormatting
Selection.MoveDown Unit:=wdLine, Count:=2
Selection.MoveRight Unit:=wdCell, Count:=3
Selection.MoveDown Unit:=wdLine, Count:=24, Extend:=wdExtend
Selection.Paste 'want to paste cells

Any help would be appreciated.

Jake

fumei
02-16-2009, 01:25 PM
1. do you want to paste the cells...or the contents of the cells.

2. use Range, not Selection.

Are these known cells? If they are, bookmark them and use the bookmarks to get the contents. Or, make a Cell object, and collect the contents that way.

BTW:
ActiveWindow.Close 'closes document2
that does NOT close document 2. It switches windows. The document is NOT closed.

If you used Range, you do not have to switch between windows at all.

If your tables are themselves bookmarked, you can create and use a Table object, and that will make it even easier.

Also, use Document objects...well, actually use objects.

Let's run through an example.

Document1 has a table.
Document2 has a table.

Both of them are open.

You want to get the contents of cell(3,2) of Table2 in Document2 and put that into cell(5,2) of Table5 in Document1. The code below does precisely that.
Option Explicit

Sub getStuff()
Dim SourceDoc As Document
Dim CopyToDoc As Document
Dim oTable1 As Table
Dim oTable2 As Table
Dim oCell As Cell

' set the document objects
Set SourceDoc = Documents("TestDoc2.doc")
Set CopyToDoc = Documents("TestDoc1.doc")

' set the table objects
Set oTable1 = SourceDoc.Bookmarks("Doc2Table2") _
.Range.Tables(1)
Set oTable2 = CopyToDoc.Bookmarks("Doc1Table5") _
.Range.Tables(1)

' set cell object to the cell in table2, Document2
Set oCell = oTable1.Cell(3, 2)

' make Document2, Table5, cell(5,2) THAT value
oTable2.Cell(5, 2).Range.Text = _
oCell.Range.Text
End Sub

bigjaker
02-17-2009, 12:51 PM
Fumei,

Thanks for the response. I will take your code and work it into mine. Seems much shorter and easier then what I was trying to do.

Thanks as well for the teaching you do here as well. You have definately helped me in other posts of yours.

Jake