Option Explicit
Sub InsertLine1()
Dim wrdDoc As Word.Document
Dim wrdTable1 As Word.Table
Dim wrdTable2 As Word.Table
Dim wrdRow1 As Word.Row
Dim wrdRow1a As Word.Row
Dim wrdRow2 As Word.Row
Dim wrdRange As Word.Range
Dim wrdCell As Word.Cell
Dim f As Integer
Dim c As Integer
Dim wrdField As Word.Field
Dim wrdFormField1 As Word.FormField
Dim wrdFormField2 As Word.FormField
Dim strTitle As String
Dim strNewTitle As String
'table 1 contains the selection
Set wrdTable1 = Selection.Tables(1)
strTitle = GetCellText(wrdTable1.Range.Cells(1))
strNewTitle = Replace(strTitle, "MP ", "PW ")
'find matching table
For Each wrdTable2 In ActiveDocument.Tables
If GetCellText(wrdTable2.Range.Cells(1)) = strNewTitle Then
Exit For
End If
Next wrdTable2
'debugging message
If wrdTable2 Is Nothing Then
MsgBox "Matching table not found"
Exit Sub
End If
'...
Set wrdDoc = ActiveDocument
Set wrdRow1 = wrdTable1.Rows.Last
wrdDoc.Unprotect 'password
Set wrdRange = wrdRow1.Range
'add row and form fields to first table
Set wrdRow1a = wrdTable1.Rows.Add
For f = 1 To wrdRow1.Range.FormFields.Count
Set wrdFormField1 = wrdRow1.Range.FormFields(f)
Set wrdCell = wrdFormField1.Range.Cells(1)
c = wrdCell.ColumnIndex
Set wrdRange = wrdRow1a.Cells(c).Range
wrdRange.Collapse wdCollapseStart
Set wrdFormField2 = wrdDoc.FormFields.Add(wrdRow1a.Cells(c).Range, wrdFormField1.Type)
Next f
'Add row and ref fields to second table
Set wrdRow2 = wrdTable2.Rows.Add
For f = 1 To wrdRow1a.Range.FormFields.Count
Set wrdFormField2 = wrdRow1a.Range.FormFields(f)
wrdFormField2.CalculateOnExit = True
Set wrdCell = wrdFormField2.Range.Cells(1)
c = wrdCell.ColumnIndex
Set wrdRange = wrdRow2.Cells(c).Range
wrdRange.Collapse wdCollapseStart
Set wrdField = wrdDoc.Range.Fields.Add(wrdRange, , "REF " & wrdFormField2.Name)
Set wrdFormField2 = Nothing
Next f
wrdDoc.Protect wdAllowOnlyFormFields, True ',password
End Sub
Function GetCellText(cel As Word.Cell) As String
Dim rng As Range
Set rng = cel.Range
rng.MoveEnd wdCharacter, -1
GetCellText = Trim$(rng.Text)
End Function
|