Objective
To delete all the text boxes on a slide using VBA.
Approach
Herein we have two command buttons and some text boxes on the slide 1 of PowerPoint presentation, so we are trying to delete all the text boxes, while preventing the command buttons from deletion.
A catch in code execution !
The catch here is that, if we have 5 shapes and we deleted 3rd shape i.e. shape (3), then next shape i.e. shape (4)
will be referred as shape (3) now, because its previous shape has been deleted, in simple terms once a shape is deleted, its next shape will take its shape index. So, all the other shapes will have shape index which will be 1 less as compared to its original shape index. For e.g. if shape (3) is deleted then shape (8) will now be referred as shape (7). We have used variable “shpNumber” to handle this case.
Same thing can be verified by debugging the VBA code while deleting the shapes one by one.
In the beginning slide 1 had 3 text boxes.We had a “Delete Text Box” command button, which has the below shown VBA code assigned. Refer to image below.
As we click the delete button which is shown below, all the text boxes will be deleted from slide 1, while both the command buttons will not be deleted.We can see the same in image shown below.
Below code achieves two functionalities –
1. Delete all text boxes
2. Prevent the command buttons from deletion
Steps:
- Declare variable for shape
- Loop through all the shapes in slide 1
- Check if the selected shape has text frame
- If the selected shape has text frame , then delete
- If shape has no text frame, then move to next shape
Private Sub CommandButton2_Click() Dim shpCount As Double Dim osld As Shapes Set osld = ActivePresentation.Slides(1).Shapes shpNumber = 1 For shpCount = 1 To osld.Count If ActivePresentation.Slides(1).Shapes(shpNumber).HasTextFrame Then ActivePresentation.Slides(1).Shapes(shpNumber).Delete Else shpNumber = shpNumber + 1 End If Next shpCount End Sub
Note
We can also delete other power point objects using the similar technique.This VBA code can be written in the module as well, or it can be allocated to a shape. It is dependent on the scenario.
Post you may like
Add shapes in a PowerPoint slide using VBA while taking the input from user.