Reputation: 25477
This one really annoys me! I try to close all presentations that might be opened in the background (visible or not) without the active one that executes the macro.
The Thing here is, that the For Each loop does not iterate through all files even though it schould do that:
Dim i As Integer
Dim pres As PowerPoint.presentation
' Closes most of the presentations BUT NOT ALL of them
For Each pres In PowerPoint.Application.Presentations
If pres.name <> PowerPoint.ActivePresentation.name Then
pres.Close
Set pres = Nothing
End If
Next
After that not all presentations are closed. A few are still opened! I can see that Close
gets called, but some presentations stay opened.
So - knowing this is not a nice solution - I tried to iterate again over all presentaions. This time using the PowerPoint.Application.Presentations.Count
property. But all it does is running into a
For i = 1 To PowerPoint.Application.Presentations.Count
Dim name As String
Set pres = PowerPoint.Application.Presentations(i)
If pres.name <> PowerPoint.ActivePresentation.name Then
pres.Close
Set pres = Nothing
End If
Next
I have no idea what I am doing wrong here on this one.
This is not an option! :D
While PowerPoint.Application.Presentations.Count > 1
For Each pres In PowerPoint.Application.Presentations
If pres.name <> PowerPoint.ActivePresentation.name Then
pres.Saved = 1
pres.Close
Set pres = Nothing
End If
Next
Wend
Upvotes: 1
Views: 1705
Reputation: 1
Sub CloseAllOtherPresentation()
Dim ChooseButton As VbMsgBoxResult
ChooseButton = MsgBox("WARNING!! All opened presentation will close,Continue?", vbYesNo, "")
If ChooseButton = vbYes Then
Dim i As Integer
For i = Presentations.Count To 1 Step -1
If Presentations(i).Name <> ActivePresentation.Name Then
Presentations(i).Save
Presentations(i).Close
End If
Next
End If
End Sub
When you delete an item from a collection, the index of the collections updates eg. A=1 , B=2, C=3, D=4 E=5 F=6 [A-F are objects,numbers are the index]. for iteration function, the counter increases let say CT represent counter. WHEN FOR LOOP IS USED to remove Objects in a forward manner :)
CT=1, A is removed, arrangement now is
B=1, C=2, D=3 E=4 F=5
CT=2, C will be remove because is now the second item, hence we have
B=1, D=2 E=3 F=4
CT=3 ?, and so on. At the end instead of deleting all it leaves
B=1,D=2,F=3
Because of this, in removing objects from collection, we start from backward
Upvotes: 0
Reputation: 17495
In order to properly remove objects from a collection (which Presentations
is), you need to go backwards. If not, the item gets removed from the collection, every item "behind" it gets shifted forward - but then you increase the counter and therefore skip one!
Therefore, try this:
For i = Presentations.Count To 1 Step -1
If Presentations(i).Name <> _
ActivePresentation.Name Then
Presentations(i).Close
End If
Next
Upvotes: 3