PowerPoint VBA: which command (or a set of commands) would create ppt frames out of my .jpg pictures? - vba

I have a few .jpg files in C:\my_folder
Here are their names: pic_1.jpg , pic_2.jpg , pic_3.jpg , pic_4.jpg , pic_5.jpg .
What command or a group of commands in Power Point VBA should I use in order to be able to automatically create several frames in PowerPoint so that each frame would contain one picture?

This VBScript creates a new PowerPoint presentation and adds two slides to it, each with a picture. You will need to adjust the picture's location and size to suit your taste. Also you'll need to utilize the Scripting.FileScriptingObject to enumerate your images if you want to automatically grab whatever pictures exist in a directory for embedding into the presentation. If you want your script can also save the presentation by calling pptPresentation.SaveAs after your slides are generated.
The MSDN documentation is located at http://msdn.microsoft.com/en-us/library/ff746873.aspx.
Dim pptDoc
Dim pptPresentation
Dim pptSlide
Set pptDoc = WScript.CreateObject( "PowerPoint.Application" )
pptDoc.Visible = True
Set pptPresentation = pptDoc.Presentations.Add( True )
' Add a new slide with a blank layout to the end of the Slides collection
' 12 = ppLayoutBlank
Set pptSlide = pptPresentation.Slides.Add( pptPresentation.Slides.Count + 1, 12 )
' Add a picture into the slide, saving the picture into the PowerPoint document
' 10, 10 are the Left and Top coordinates respectively
pptSlide.Shapes.AddPicture "c:\FullPath\1.JPG", False, True, 10, 10
' Add another slide with a picture
Set pptSlide = pptPresentation.Slides.Add( pptPresentation.Slides.Count + 1, 12 )
pptSlide.Shapes.AddPicture "c:\FullPath\2.jpg", False, True, 10, 10

As the previous answer was specific to VBS scripting, here is a version for embedding into PowerPoint as a VBA macro. This was created with PowerPoint 2010.
This has the directory hard-coded so it's an exercise for the reader to prompt for a directory name to scan.
Sub CreatePictureSlideshow( )
Dim presentation
Dim layout
Dim slide
Dim FSO
Dim folder
Dim file
Dim folderName
' Set this to point at the folder you wish to import JPGs from
' Note: make sure this ends with a backslash \
folderName = "c:\somedirectory\"
' Delete all slides and setup variables
Set presentation = Application.ActivePresentation
If presentation.Slides.count > 0 Then
presentation.Slides.Range.Delete
End If
Set layout = Application.ActivePresentation.SlideMaster.CustomLayouts(1)
Set FSO = CreateObject("Scripting.FileSystemObject")
' Retrieve the folder's file listing and process each file
Set folder = FSO.GetFolder(folderName)
For Each file In folder.Files
' Filter to only process JPG images
If LCase(Mid(file.Name, Len(file.Name) - 3, 4)) = ".jpg" Then
' Create the new slide and delete any pre-existing contents
Set slide = presentation.Slides.AddSlide(presentation.Slides.count + 1, layout)
While slide.Shapes.count > 0
slide.Shapes(1).Delete
Wend
' Add the picture
slide.Shapes.AddPicture folderName + file.Name, False, True, 10, 10
' Optional: create a textbox with the filename on the slide for reference
' Dim textBox
' Set textBox = slide.Shapes.AddTextbox(msoTextOrientationHorizontal, 10, 10, 200, 200)
' textBox.TextFrame.TextRange.Text = file.Name
End If
Next
End Sub

Related

VB code to create slides based on number of audio files, and insert random background images

I am trying to create a VB Code that will create number of slides based on the audio files in the folder.
Then, I want to insert random background images from the folder.
I have written this code but it doesn't work.
Sub CreatePowerPointSlides()
'Declare variables
Dim pptApp As Object
Dim pptPres As Object
Dim pptSlide As Object
Dim audioFiles As String
Dim audioFile As String
Dim imageFiles As String
Dim imageFile As String
'Create a new instance of PowerPoint and open the presentation
Set pptApp = CreateObject("PowerPoint.Application")
pptApp.Visible = True
Set pptPres = pptApp.Presentations.Add
'Get a list of all audio files in the folder
audioFiles = Dir("C:\Users\audio\*.mp3")
'Iterate through each audio file in the folder
Do While audioFiles <> ""
audioFile = audioFiles
'Create a new slide in PowerPoint and add the audio file
Set pptSlide = pptPres.Slides.Add(pptPres.Slides.Count + 1, 11, ppViewSlide)
pptSlide.Shapes.AddMediaObject2 FileName:=audioFile, LinkToFile:=msoFalse,
SaveWithDocument:=msoTrue
'Get a list of all image files in the folder
imageFiles = Dir("C:\Users\user1\Pictures\ImageBackground\Nature\*.jpg")
'Choose a random image file from the folder
Randomize
imageFile = "C:\Users\user1\Pictures\ImageBackground\Nature\" &
Split(imageFiles, vbNewLine)(Int(Rnd() *
UBound(Split(imageFiles, vbNewLine))))
'Add the image file as the background of the slide
pptSlide.FollowMasterBackground = msoFalse
pptSlide.Background.Fill.UserPicture PictureFile:=imageFile
'Get the next audio file in the folder
audioFiles = Dir()
Loop
pptApp.ActiveWindow.View.Type = ppViewSlide
End Sub
It doesn't even create one slide.

How to copy objects from a VISIO file to the same location in another file

I created a VBA program to copy from one VISIO file (A.vsdx) to another VISIO file (B.vsdx) using the Selection.Copy method.
I want to copy it to the same location as the A.vsdx file, but it doesn't work. It was
https://learn.microsoft.com/en-us/office/vba/api/visio.page.paste
Looking at this page, visCopyPasteNoTranslate seems to be good, but it didn't work as expected.
Alternatively, I considered using the Selection.Top method, but it didn't work because VISIO's Selection doesn't have a Top or Left method.
The pseudo code is shown below.
Dim group_ As visio.Shape
For Each vsoPage In vsoDoc.Pages
vsoWindow_old.Page = vsoDoc.Pages.ItemU(vsoPage.NameU)
vsoWindow_new.Page = newvsoDoc.Pages.ItemU(vsoPage.NameU)
For Each vsoShape In vsoPage.Shapes
vsoWindow_old.Selection.Select vsoShape, visSelect
Next vsoShape
If Not (vsoWindow_old.Selection Is Nothing) Then
''' This code doesn't work
Set group_ = vsoWindow_old.Selection.group
'''
vsoWindow_old.Selection.Copy
newvsoDoc.Pages.Item(vsoPage.Name).Paste visCopyPasteNoTranslate
End If
vsoWindow_old.Selection.DeselectAll
Next vsoPage
You can use method PasteToLocation, but you must know X,Y-coordinates for paste!
I wrote the code hastily, for a simplified case:
both documents contain only single page
the target document has a blank page (no shapes)
target page have not locked layers [updated]
Sub For_user18616709()
Dim s_d As Document ' source document
Dim t_d As Document ' target document
Dim s_p As Page ' source document
Dim t_p As Page ' target document
Dim gr As Shape ' temprery shape for copy
Dim sl As Selection ' Selection
Dim shs As Shape ' temprery shape after paste
Dim xp As Double, yp As Double ' X, Y coordinates
Set s_d = ActiveDocument ' define source doc
Set s_p = s_d.Pages(1) ' define source page
Set t_d = Documents(2) ' define target doc
ActiveWindow.SelectAll ' Select all shapes at source page
Set sl = ActiveWindow.Selection ' define sl
Set gr = sl.Group ' define temprery shape for copy
xp = gr.Cells("PinX") ' define X-coordinate of temprery shape
yp = gr.Cells("PinY") ' define Y-coordinate of temprery shape
gr.Copy ' copy to clipboard temprery shape for copy
gr.Ungroup ' destroy temprery shape for copy
Set t_p = t_d.Pages(1) ' define target page
t_p.PasteToLocation xp, yp, 0 ' paste to target page with location
Set shs = t_p.Shapes(1) ' define temprery shape after paste
shs.Ungroup ' destroy temprery shape after paste
End Sub

Running VBA code on external powerpoint file

I want to run VBA code from a certain powerpoint file on an external powerpoint file without copying the code into the external powerpoint file. I wish to only open the original powerpoint file containing the code and run it from there, it should point to the external powerpoint file and alter it directly. How to do this?
So far I am doing it like this:
'For each file, if powerpoint run remove alt text macro
For Each FSOFile In FSOFolder.Files
'Insert the actions to be performed on each file
sFileExtension = FSOFile.GetExtensionName()
If sFileExtension = "pptm" Or sFileExtension = "pptx" Or sFileExtension = "ppt" Then
Dim PPT As Object
Set PPT = CreateObject("PowerPoint.Application")
PPT.Presentations.Open (FSOFile.Path)
' Note that the file name and the module
' name are required to path the macro correctly.
PPT.Run (ActivePresentation.Path + "!Module1.BlankAllTheAltText")
filesAltered = filesAltered + 1
End If
Next
I don't think this is correct. Any suggestions?
Since you're already running this from within PPT, you don't need to create a PPT application object. Try something more like this:
Dim oPres As Presentation
'For each file, if powerpoint run remove alt text macro
For Each FSOFile In FSOFolder.Files
'Insert the actions to be performed on each file
sFileExtension = FSOFile.GetExtensionName()
If sFileExtension = "pptm" Or sFileExtension = "pptx" Or sFileExtension = "ppt" Then
Set oPres = Presentations.Open(FSOFile.Path)
' Alter BlankAllTheAltText to take a presentation object
' as a parameter
Call BlankAllTheAltText(oPres)
filesAltered = filesAltered + 1
oPres.Save
oPres.Close
End If
Next

How to import bulk pictures in Power Point from folder using Open Dialogue Box to Select Entire Folder and Make New Slide for each Picture

I am trying to automate Powerpoint presentation. I found a code on the internet. This code is working well, but it works with the static path in the code. I want to implement it using OpenFolder Dialogue Box. The idea is as, When I click the button import picture, the file dialogue box should be open and I select the folder. The pictures within the folder automatically and the size of the picture should automatically fit the slide. When this process complete, the slide show automatically starts to display the picture using fade animation. The code is as under.
Sub main()
Dim i As Integer
Dim arrFilesInFolder As Variant
arrFilesInFolder = GetAllFilesInDirectory("C:\Users\Admin\OneDrive\Pictures\Screenshots")
For i = LBound(arrFilesInFolder) To UBound(arrFilesInFolder)
Call AddSlideAndImage(arrFilesInFolder(i))
Next
End Sub
Private Function GetAllFilesInDirectory(ByVal strDirectory As String) As Variant
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim arrOutput() As Variant
Dim i As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder(strDirectory)
ReDim arrOutput(0)
i = 1
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'print file path
arrOutput(i - 1) = objFile.Path
ReDim Preserve arrOutput(UBound(arrOutput) + 1)
i = i + 1
Next objFile
ReDim Preserve arrOutput(UBound(arrOutput) - 1)
GetAllFilesInDirectory = arrOutput
End Function
Private Function AddSlideAndImage(ByVal strFile As String)
Dim objPresentaion As presentation
Dim objSlide As slide
Set objPresentaion = ActivePresentation
Set objSlide = objPresentaion.Slides.Add(1, PpSlideLayout.ppLayoutChart)
Call objSlide.Shapes.AddPicture(strFile, msoCTrue, msoCTrue, 100, 100, 650, 450)
End Function
Please someone guide, where I am doing wrong. Thanks
Looks like you need to replace the hard-coded file path with code that prompts the user for one. Seems Application.FileDialog should get you there:
Dim path As String
With Application.FileDialog(Type:=msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show Then
path = .SelectedItems(1)
Else
'user cancelled, bail out:
Exit Sub
End If
End With
Dim arrFilesInFolder As Variant
arrFilesInFolder = GetAllFilesInDirectory(path)
'...rest of the code...

OnSlideShowPageChange not running in presentation

I have been tasked with building an automated powerpoint to show new employees during onboarding. I decided to use the text-to-speech function of PPT to narrate the show. I came to the realization that this would require code, so I searched and found some code to use. When I start it within VBA, it runs. However, when in presentation mode, it doesn't fire the code. After hours of searching, I can't seem to find what I've done wrong. Any help is greatly appreciated.
Function SpeakThis(myPhrase As String)
Dim oSpeaker As New SpeechLib.SpVoice
'Set speech properties
oSpeaker.Volume = 100 ' percent
oSpeaker.Rate = 0.1 ' multiplier
oSpeaker.SynchronousSpeakTimeout = 1
oSpeaker.AlertBoundary = SVEWordBoundary
If Not myPhrase = "" Then oSpeaker.Speak myPhrase, SVSFDefault
End Function
Sub OnSlideShowPageChange()
Dim text As String
Dim intSlide As Integer
intSlide = ActiveWindow.Selection.SlideRange.SlideIndex
text = ActivePresentation.Slides(intSlide).NotesPage.Shapes.Placeholders(2).TextFrame.TextRange.text
SpeakThis text
End Sub
To get the current slide index, you can use the following:
In Slide View mode: ActiveWindow.View.Slide.SlideIndex
In Slide Show mode: ActivePresentation.SlideShowWindow.View.Slide.SlideIndex
For this to work in presentation mode, change
intSlide = ActiveWindow.Selection.SlideRange.SlideIndex
to
intSlide = ActivePresentation.SlideShowWindow.View.Slide.SlideIndex
Note that this throws an error if not in presentation mode.
EDIT: In simplified form, you could also do this:
Sub OnSlideShowPageChange(ByVal Wn As SlideShowWindow)
SpeakThis Wn.View.Slide.NotesPage.Shapes.Placeholders(2).TextFrame.TextRange.text
End Sub
Here I introduce MY work-around which can meet what you want.
Actually, you can save above TTS sound into an .wav file
which can be inserted and played on entering each slide.
Since you want to play some narration sound on each slide,
I suggest you to convert all the notes into .wav files and insert them as normal audio effects.
To automate the process, I wrote some code.
First, to save each note in an .wav file (given the slide index)
'save the slide's note in a .wav file
'You need to add reference to 'Microsoft Speech Object Library' (*required*)
Function SaveTTSWav(idx As Long)
Const SAFT48kHz16BitStereo = 39
Const SSFMCreateForWrite = 3
Dim oSpeaker As New SpeechLib.SpVoice
Dim oStream As New SpeechLib.SpFileStream
oStream.Format.Type = SAFT48kHz16BitStereo
'filename to save: ex) note1.wav
oStream.Open ActivePresentation.Path & "\note" & idx & ".wav", SSFMCreateForWrite, False
oSpeaker.Volume = 100 '%
oSpeaker.Rate = 1 '1x speed
oSpeaker.SynchronousSpeakTimeout = 1
oSpeaker.AlertBoundary = SVEWordBoundary
Set oSpeaker.AudioOutputStream = oStream
oSpeaker.Speak ActivePresentation.Slides(idx).NotesPage.Shapes.Placeholders(2).TextFrame.TextRange.text, SVSFNLPSpeakPunc
oStream.Close
End Function
Then, Insert the 'note(X).wav' files in each slide and add animation effects to them:
'insert the .wav and make it play automatically
Function AddTTSMedia(idx As Long)
Dim sld As Slide
Dim shp As Shape
Dim eft As Effect
Dim wavfile As String
wavfile = ActivePresentation.Path & "\note" & idx & ".wav"
If Len(Dir(wavfile)) = 0 Then Exit Function
Set sld = ActivePresentation.Slides(idx)
Set shp = sld.Shapes.AddMediaObject2(wavfile, False, True, 0, 0, 20, 20)
'shp.Name = Mid(wavfile, InStrRev(wavfile, "\") + 1) '.wav filename
Set eft = sld.TimeLine.MainSequence.AddEffect(shp, msoAnimEffectMediaPlay, , msoAnimTriggerWithPrevious)
eft.MoveTo 1 'make it the first effect
With eft.EffectInformation.PlaySettings 'shp.AnimationSettings.PlaySettings
.HideWhileNotPlaying = True
.PauseAnimation = False
.PlayOnEntry = True
.StopAfterSlides = 1
End With
'Kill wavfile
End Function
Finally, make it happen on every slide:
Sub Add_TTS_Notes()
Dim sld As Slide
'Remove previously inserted note sounds
RemoveNoteWav
For Each sld In ActivePresentation.Slides
'save the note to an .wav file
SaveTTSWav sld.SlideIndex
'add the .wav file onto the slide
AddTTSMedia sld.SlideIndex
Next sld
'ActivePresentation.Save
End Sub
In addition, if you want to cancel and remove all note sounds from your presentation,
you can run the following code manually:
'remove all .wav media(s) in each slide
Sub RemoveNoteWav()
Dim sld As Slide
Dim i As Long
For Each sld In ActivePresentation.Slides
For i = sld.Shapes.Count To 1 Step -1
If sld.Shapes(i).Name Like "note*.wav" Then sld.Shapes(i).Delete
Next i
Next sld
End Sub
All you have to do is to copy all codes above onto your PPT's VBE editor and to run the main macro named "Add_TTS_Notes". It'll take some time to save some TTS sound files.
It will save the notes on all slides in .wav files, insert them on their slides and make them play automatically on each slide. After the job, you can remove VBA codes and save your ppt file as a .pptx or .ppsx which is more handy than a .pptm file since it doesn't require any security agreement.
I'm using PowerPoint 2016, and in my case, I've needed to modify Konahn's codes as below in SaveTTSWav function.
'Dim oSpeaker As New SpeechLib.SpVoice
Dim oSpeaker As Object Set
oSpeaker = CreateObject("SAPI.Spvoice")
&
'Dim oStream As New SpeechLib.SpFileStream
Dim oStream As Object Set
oStream = CreateObject("SAPI.SpFileStream")