Plain text being pasted instead of table

83 Views Asked by At

Using some of the code on this website, I am trying to make a simple VBA that:

  • Finds the first table in the document
  • Finds "find text"
  • Duplicates the table where "Find text" is.

However, when I try to use the code below, it pastes the contents of the table without pasting the table itself.

Can you please help??

Sub Duplicate_Table()

Dim doc As Word.Document
Dim tbl As Word.Table
Dim rngTableTarget As Word.Range

Set doc = ActiveDocument
Set tbl = doc.Tables(1)
Set rngTableTarget = doc.Content

'Copy the table to the current selection
Selection.FormattedText = tbl.Range.FormattedText

Dim rngStory As Range
   For Each rngStory In ActiveDocument.StoryRanges
   With rngStory.Find
    .ClearFormatting
    .Text = "Find text"
    .Replacement.Text = tbl.Range.FormattedText
    .Wrap = wdFindContinue
    .Execute Replace:=wdReplaceAll
End With
Next rngStory
End Sub
1

There are 1 best solutions below

0
Timothy Rylatt On BEST ANSWER

.Replacement.Text is just a string. It cannot be used to apply formatted text.

However, you can copy the table and then use Find to replace the found text with the clipboard contents.

Sub Duplicate_Table()

    Dim doc As Word.Document

    Set doc = ActiveDocument
    doc.Tables(1).Range.Copy

    Dim rngStory As Range
    For Each rngStory In ActiveDocument.StoryRanges
        With rngStory.Find
            .ClearFormatting
            .Text = "Find text"
            .Replacement.Text = "^c"
            .Wrap = wdFindContinue
            .Execute Replace:=wdReplaceAll
        End With
    Next rngStory
End Sub