Replace image inside Word bookmark from Excel

2019-07-13 08:52发布

I have an open Word document with a bunch of bookmarks, each with an inline image of an Excel table previously exported from Excel.

Now, I need to update the tables in the Word document as they have changed in Excel.

The way I'm doing this is matching the table names in Excel with the bookmark names in Word. If they are equal than I want to replace the existing images in Word by the current ones.

This is my code so far:

Sub substituir()
Set WordApp = GetObject(class:="Word.Application")
Set DocumentoDestino = WordApp.ActiveDocument

For Each folha In ThisWorkbook.Worksheets
    If folha.Visible Then

    'loop all excel tables
    For Each tabela In folha.ListObjects
        tabela.Name = Replace(tabela.Name, " ", "")
        nomeTabela = tabela.Name

        For Each myBookmark In DocumentoDestino.Bookmarks
            If Right(myBookmark.Name, 4) = "PGST" Then

              'This is where I need help
              If myBookmark.Name = nomeTabela Then
                'code to clear the table already in myBookmark here


                'then copy and paste tables in myBookmark
                tabela.Range.Copy
                myBookmark.Range.PasteSpecial link:=False, DataType:=wdPasteMetafilePicture, _
                    Placement:=wdInLine, DisplayAsIcon:=False

              End If
            End If
        Next myBookmark

     Next tabela

    End If
Next folha

End Sub

I've tried lots of different approaches, from deleting the bookmark and adding it back again to others, but nothing seems to work.

In the comment: 'code to clear the table already in myBookmark here I need help.

1条回答
来,给爷笑一个
2楼-- · 2019-07-13 09:37

In the following code, I have tried to include the syntax you might require for your project.

Private Sub TestMark()

    Dim Mark As String
    Dim Rng As Range
    Dim ShpRng As Range

    Mark = "Text1"
    With ActiveDocument
        If .Bookmarks.Exists(Mark) Then
            Set Rng = .Bookmarks(Mark).Range
            If Rng.InlineShapes.Count Then
                Set ShpRng = Rng.InlineShapes(1).Range
                With ShpRng
                    Debug.Print .Start, .End
                End With
            End If
        End If
    End With
End Sub

Of course once you know the Start and End of the range you can manipulate it, meaning delete and replace it.

It just occurs to me that you might use the InlineShape' Caption property to find and address it.

查看更多
登录 后发表回答