Search code examples
vbams-wordbookmarks

Use Find in VBA word and paste graph in next paragaraph


I am using the find option in word VBA and want to paste a graph in the next paragraph wherever i find my text.

Set myRange = ActiveDocument.Content
With myRange.Find
      .Text = "Chart"
      .Forward = True
      .Wrap = wdFindStop
      .MatchWildcards = False
       bFound = .Execute
End With
If bFound Then
       Set ChartObj = wb1.ChartObjects("Chart 1")
       ChartObj.Chart.ChartArea.Copy
       .Words.Last.Paste
End If

The .words.Last.Paste pastes the graph at the end of the document instead of pasting it at the end of word "Chart" which I am seraching. How do I instert a paragraph at the end of line where i find my text and paste the chart there ?

I also tried the bookmark approach, such that my graphs gets pasted at the next paragraph after text 'My Chart here', but don't know how to move the cursor to the end of my text and then add paragraph there.

 .Bookmarks('chart').Range.Text = 'My Chart here'

The text 'My chart here' has more than 1 character but when i use the code below i only get 1 as answer. What I am missing here ?

  Msgbox .Bookmarks('chart').Range.Characters.Count

Solution

  • .Words is a property of the Range object, so you need to use myRange.Words.Last.Paste


    Sub test()
        Set myRange = ActiveDocument.Content
        With myRange.Find
            .Text = "Insert"
            .Forward = True
            .Wrap = wdFindStop
            .MatchWildcards = False
            bFound = .Execute
        End With
        If bFound Then
            Set ChartObj = wb1.ChartObjects("Chart 1")
            ChartObj.Chart.ChartArea.Copy
            myRange.Words.Last.Paste
        End If
    End Sub|