Search code examples
vbapowerpoint

Insert Powerpoint image via VBA without defined file path


Is it possible to have a variable file-path in order to upload an image in PowerPoint? I want the user to specify the file path using the 'file-picker' dialogue pop-up. So that the user can browse the computer like a normal file upload.

Notice that in my code I need to specify the path of the file and since this presentation will be used by more than one person, I cannot define a path and name.

I attached a print and also the code snippet.

Sub uploadImg()
Dim tgtSlide As Slide
Dim prj As Shape

Dim sld As Slide
Dim picPath As String

Set sld = ActivePresentation.SlideShowWindow.View.Slide
Set tgtSlide = ActivePresentation.Slides(sld.SlideIndex + 0)

'get the presentation save path first
picPath = ActivePresentation.Path
'define the image full path
picPath = picPath & "/imagens/capturar.png"

'add a linked image/shape to target slide
'Set prj = tgtSlide.Shapes.AddPicture(picPath, msoTrue, msoTrue, Left:=500, Top:=130, Width:=190, Height:=105)
Set prj = tgtSlide.Shapes.AddPicture(picPath, msoTrue, msoTrue, Left:=500, Top:=130)
    With prj
        .LockAspectRatio = msoTrue 'can be set to msoFalse if you don't need to lock aspect ratio
        '.Width = 190
        .Height = 105
    End With

prj.LinkFormat.Update

'goes to the target slide
ActivePresentation.SlideShowWindow.View.GotoSlide (tgtSlide.SlideIndex)
End Sub

Solution

  • You can allow the user to define a path and store it in Location:

    Application.FileDialog(msoFileDialogFilePicker).Show
    Dim Location As String
    Location = Application.FileDialog(msoFileDialogFilePicker).SelectedItems(1)
    
    'define the image full path
    picPath = Location