Link to home
Start Free TrialLog in
Avatar of isurgyn
isurgyn

asked on

Delete Shapes from Word Macro Enabled Template using VBA

Hi,

I have a Macro-Enabled Word Template that I have some shapes inserted.  When I go to save the document I would like to delete some of the shapes but not all of the shapes.

The following code deletes all of the shapes.  Is there a way to name the shapes individually so that they can be deleted in groups?


    Dim strToPath As String
    Dim strMsg As String
    Dim iResponse As Integer
    Dim i As Integer
   
    strToPath = Me.FormFields("strToPath").Result
     
 
    strMsg = strMsg & "If these steps are complete then select 'OK' to" & Chr(10)
    strMsg = strMsg & "permanently save the form to your file" & Chr(10)
    strMsg = strMsg & "or select 'Cancel' to return to the form." & Chr(10)
   
    iResponse = MsgBox(strMsg, vbOKCancel, "Final Instructions Prior to Saving Form")
   
        If iResponse = vbCancel Then
            Exit Sub
        End If

       'Delete ActiveX Command Button

          SaveEnhPolicy.Select
          Selection.Delete
   
          'Delete Shapes

         For i = ActiveDocument.Shapes.Count To 1 Step -1
         ActiveDocument.Shapes(i).Delete
         Next i

    ActiveDocument.SaveAs FileName:=strToPath, _
        FileFormat:=wdFormatPDF
   
    With Application
   
        .ScreenUpdating = True
        .Quit SaveChanges:=wdDoNotSaveChanges
       
    End With
ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of isurgyn
isurgyn

ASKER

Hi Graham,

Thanks the code snippets look great.  In the time waiting for a solution I created a quick and dirty fix that didn't require naming the shapes but I will come back later and try your code as it will be a better solution for future projects.

What I did is just manipulate the shape count in a way that allowed me to delete unwanted shapes and keep the ones that I wanted.  A little trial and error to do so but only about 10 minutes of total time to move forward.

Thanks again.  Here is my quick fix.

    For i = ActiveDocument.Shapes.Count - 1 To 2 Step -1
    ActiveDocument.Shapes(i).Delete
    Next i