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

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.

Related

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...

vbCFBitmap Variable Not defined

I am using MS-Access 2007 VBA.
I am attempting to convert a pdf to an image. I found this chunk of code online, but they failed to provide all the references. My compile is failing on vbCFBitmap. Does anyone know where this reference comes from?
Dim MyAcro As New AcroApp
Dim MyPDF As New AcroPDDoc
Dim MyPage As AcroPDPage
Dim MyPt As acrobat.AcroPoint
Dim MyRect As AcroRect
Dim MyData As DataObject
Dim strPathString As String
Dim MyPath As String
Dim SaveToPath As String
Dim mysavepath As String
MyPath = "\\spfs1\stone\Long Term Share\gentex_ppaps\gentex_ppaps_raw\Supplier Request Number 3034910, Gentex Part Number 345-2120-000 Revision (003).pdf"
mysavepath = "C:\out"
' open the PDF
MyPDF.Open (MyPath)
Set MyPage = MyPDF.AcquirePage(0)
' Convert Point to Twips for document
Set MyPt = New AcroPoint
'Define the rectangle that contains the PDF form
Set MyRect = New acrobat.AcroRect
MyRect.Top = 0
MyRect.Left = 0
MyRect.Right = MyPt.x
MyRect.bottom = MyPt.y
' Copy the PDF image to the clip board
Call MyPage.CopyToClipboard(MyRect, MyRect.Left, MyRect.Top, 100)
' Capture image from clip board to data object
Set MyData = Clipboard.GetData(vbCFBitmap)
'Save the data object
SavePicture MyData, mysavepath
' Clean up
Set MyAcro = Nothing
Set MyPDF = Nothing
Set MyPage = Nothing
Set MyPt = Nothing
Set MyRect = Nothing
Set MyData = Nothing
That's likely VB6 code, not VBA.
vbCFBitmap is a system global, and thus not imported using any references.
However, that's just a copy of the Windows Standard Clipboard Formats, thus vbCFBitmap is equal to 2. You can use 2 instead.

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")

Export single CATIA body from CATPart as stl using VBA macro

Is it possible to export a single CATIA body as STL without creating a separate part with it?
For the time being, I have coded a script which loops through the CATParts present in a folder, fetches the contained bodies and create a single CATPart with each of them and export into stl format.
Dim output_stl_path_HD As String
Dim output_stl_path_MD As String
Dim output_stl_path_SD As String
Dim output_stl_path_via_points As String
Dim output_transformations_path As String
Dim input_path As String
Sub CATMain()
'Path for output file
input_path = CATIA.ActiveDocument.path + "\"
Dim it As Integer
Dim prod As Product
Dim t_p_ref(11)
'List of part names to export
Dim list As Collection
Set list = New Collection
'GET LIST OF CATPART IN FOLDER
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder(input_path)
i = 1
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'print file name
If (InStr(objFile.path, ".CATPart")) Then
list.Add (objFile.name)
' Set objDocument = CATIA.Documents.Open(objFile.path)
Dim srcDoc As PartDocument
Set srcDoc = CATIA.Documents.Open(objFile.path)
Dim srcPart As Part
Set srcPart = srcDoc.Part
Dim oSel As Selection
Dim bodies1 As Bodies
Dim body1 As body
'
Set bodies1 = srcPart.Bodies
For Each single_body In srcPart.Bodies
A = exportStl(single_body)
Next
Set body1 = srcPart.Bodies.Item(i)
'Dim BoxProduct
'BoxProduct = MsgBox("Quantity of the bodies found:" & srcDoc.Part.Bodies.Count & "", 64)
End If
Next
End Sub
Public Function exportStl(ByVal myBody As body)
Dim oSrc As Part
Dim oTgt As Part
Dim oSrcDoc As PartDocument
Dim oTgtDoc As PartDocument
Dim oBod As body
Dim oSel As Selection
'Sets documents for Source and Target files
Set oSrcDoc = CATIA.ActiveDocument
Set oTgtDoc = CATIA.Documents.Add("Part")
oTgtDoc.Product.PartNumber = myBody.name
'Gets Body to copy
Set oSrc = oSrcDoc.Part
Set oTgt = oTgtDoc.Part
Set oBod = myBody
Set oSel = oSrcDoc.Selection
'Copies Body
oSel.Add oBod
oSel.Copy
Set oSel = oTgtDoc.Selection
'Sets and Pastes in Target file as result with link
oSel.Clear
oSel.Add oTgt.Bodies.Item(1)
oSel.Paste
oSrcDoc.Selection.Clear
CATIA.ActiveDocument.ExportData input_path + myBody.name, "stl"
CATIA.ActiveDocument.Close
End Function
Catia V5 is capable of creating STL files from parts (CatiaPART files), but not from assemblies (CatiaPRODUCT files) or geometrical representations (car files). Therefore, source files, including those saved in a neutral format (STEP or IGES, for example), must be saved as parts. If the source design was saved as an assembly, it is imported to Catia as a product. -
Source : http://www.stratasys.com/customer-support/cad-to-stl/catia
I tried exporting CATBody but was unsuccessful. We must have a CATPart to generate STL

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

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