Emil Brundage
Emil Brundage

Reputation: 213

Trouble with VBA Do While loop in macro to copy slide and change picture in powerpoint

I am attempting my first macro in powerpoint. I am simply trying to copy a 'reference' slide and replace one picture. I will do this for all pictures in a folder. The script I have adds all the slides, but then adds all the pictures to the final slide. I don't understand why this is the case since the Duplicate Slide code and the Add Picture code are in the same while loop. Can someone tell me why?

Sub LoopThroughFiles() 
    Dim StrFile As String 
    Dim Folder As String 
    Dim sld As Slide 
    Dim referencesld As Slide 
    Set referencesld = ActivePresentation.Slides(1) 
    Dim i As Integer 
    Dim shp As Shape 
    i = 1 
    Folder = "c:\E1B8\ScriptTesting\MISC\PPT\SampleData2\" 
    StrFile = Dir(Folder & "*") 
    Set referencesld = ActivePresentation.Slides(1) 
    Set shp = referencesld.Shapes(5) 
    Do While Len(StrFile) > 0 
        Debug.Print Folder & StrFile 
        referencesld.Duplicate 
        i = i + 1 
        Set sld = ActivePresentation.Slides(i) 
        With shp 
            sld.Shapes.AddPicture(Folder & StrFile, msoFalse, msoTrue, .Left, .Top, .Width, .Height).IncrementRotation 360# 
        End With 
        sld.Shapes(5).Delete 
        StrFile = Dir 
    Loop 
End Sub 

Thanks!!

Upvotes: 0

Views: 565

Answers (1)

fbiazi
fbiazi

Reputation: 387

You can use a variable when duplicating the slide, forget the "i" variable, it is not needed:

delete the lines

referencesld.Duplicate 
i = i + 1 
Set sld = ActivePresentation.Slides(i)

An insert "Set sld = referencesld.Duplicate" in the place

...
Debug.Print Folder & StrFile
Set sld = referencesld.Duplicate
With shp
  sld.Shapes.AddPicture(Folder & StrFile, msoFalse, msoTrue, .Left, .Top, .Width, .Height).IncrementRotation 360#
End With
...

Untested

You can see "Duplicate" reference in http://msdn.microsoft.com/library/office/ff745804(v=office.15).aspx

Aside: I think it is weird to use the "with" keyword on the argument (shape) instead of the object you are working on (the slide).

[edited: Make it clear to understand what to do]

I hope to help.

Upvotes: 1

Related Questions