Log in

View Full Version : [SOLVED:] copy paste table issue



Kilroy
05-29-2019, 12:59 PM
Let me start by saying I know this code is inefficient. It copies table 2 and pastes a copy of below table 2. What I'm trying to figure out is how do I get it paste without adding to table 2? I need to have a paragraph marker in between them. Any thoughts on how to do this and maybe how to make the code more efficient?


Private Sub CommandButtonSectionB_Click()
'
Dim oTable As Table
Dim oRng As Range
Dim oLastCell As Range
Dim sResult As String
Dim iRow As Integer
Dim iCol As Integer
Dim sPassword As String
sPassword = "" 'This is the password used to protect/unprotect form
With ActiveDocument
.Unprotect Password:=sPassword 'Unprotect document
Set oTable = .Tables(2) 'Select the second table in the document
iRow = (oTable.Rows.Count) 'Set iRow to the last row in the supporting document section
iCol = 2
Set oLastCell = oTable.Range 'Record the row
sResult = oLastCell.FormFields(1).Result 'Get the value in the row
Set oRng = oTable.Range 'Add the last row to a range
oRng.Copy 'Copy the row
oRng.Collapse wdCollapseEnd 'Collapse the range to its end
oRng.Select 'the end of the table
Selection.MoveDown Unit:=wdLine, Count:=2, Extend:=wdExtend
Selection.MoveUp Unit:=wdLine, Count:=2, Extend:=wdExtend

Selection.Paste 'Paste the row at the end of the table

.Protect NoReset:=True, Password:=sPassword, _
Type:=wdAllowOnlyFormFields 'Reprotect the controlled form
'Selection.InsertBreak Type:=wdColumnBreak
End With
End Sub

gmayor
05-30-2019, 04:16 AM
There are some variables in your code that are unused or have no apparent purpose; however the following is an improvement and will do what you require


Private Sub CommandButtonSectionB_Click()'
Dim oTable As Table
Dim oRng As Range
Dim iRow As Integer
Dim sPassword As String
sPassword = "" 'This is the password used to protect/unprotect form
With ActiveDocument
If Not .ProtectionType = wdNoProtection Then
.Unprotect Password:=sPassword 'Unprotect document
End If
Set oTable = .Tables(2) 'Select the second table in the document
iRow = oTable.Rows.Count 'Set iRow to the last row in the supporting document section
Set oRng = oTable.Range 'Add the last row to a range
oRng.Collapse wdCollapseEnd 'Collapse the range to its end
oRng.FormattedText = oTable.Range.FormattedText
oTable.Rows(iRow + 1).Select
Selection.SplitTable
.Protect NoReset:=True, Password:=sPassword, _
Type:=wdAllowOnlyFormFields 'Reprotect the controlled form
End With
Set oTable = Nothing
Set oRng = Nothing
End Sub

Kilroy
05-30-2019, 08:44 AM
Thanks Graham. I was adding the lines below in a lame attempt to include the 2 empty paragraphs before and after the table:


Selection.MoveDown Unit:=wdLine, Count:=2, Extend:=wdExtend
Selection.MoveUp Unit:=wdLine, Count:=2, Extend:=wdExtend

I have been scouring the web and cannot find anything to accomplish my task.