Search code examples
vbaimagepowerpoint

PowerPoint Leaving Blue Background on .png Images Inserted With VBA


I have this snippet of a macro for powerpoint that inserts images:

Sub InsertRandomPictures()
    Dim fso As Object
    Dim folder As Object
    Dim file As Object
    Dim pptSlide As Slide
    Dim pic As shape
    Dim folderPath As String
    Dim randomWidth As Single, randomHeight As Single
    Dim aspectRatio As Single
    Dim tempPic As shape
    Dim counter As Integer
    
    ' Set the path to the folder containing the pictures
    folderPath = "my/path/to/folder"
    
    ' Set up FileSystemObject
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(folderPath)
    
    ' Reference slide 2
    Set pptSlide = ActivePresentation.Slides(2)
    
    ' Loop through each file in the folder
    For Each file In folder.Files
        ' Check if the file is a picture by looking at its extension
        If LCase(Right(file.Name, 3)) = "jpg" Or LCase(Right(file.Name, 3)) = "png" Or LCase(Right(file.Name, 3)) = "gif" Then        
            
            ' Insert the picture onto slide 2
            Set pic = pptSlide.Shapes.AddPicture( _
                fileName:=folderPath & file.Name, _
                LinkToFile:=msoFalse, _
                SaveWithDocument:=msoTrue, _
                Width:= 100, _
                Height:= 100)
                
            ' Set a random transparency value
            pic.Fill.Transparency = Rnd() * 0.9         
        End If
    Next file
End Sub

However, it's leaving my .png images and .gifs with transparancy with this ugly blue fill . When I manually insert the same picture, it looks fine.

(see picture)

How do I get rid of this?


Solution

  • It comes from the following code when dealing with a PNG image featuring a transparent background:

    pic.Fill.Transparency = Rnd() * 0.9

    As of now, there isn't a property accessible for managing image transparency using VBA code.

    The post also confirms it.

    Picture Transparency Object in PowerPoint VBA