Extract file names from directory into textbox Powerpoint VBA - vba

For school I am creating numerous PowerPoint presentations with pictures (hundreds to thousands) arranged such that it creates a "flashcard" like experience. I have written a code to import photos from a directory and insert the pictures separately in successive slides with the name of that picture at the bottom of the slide in the textbox. I've had no issues with that so far. However, I want to create an index page that lists all the file names, in order, but a separate lines in a textbox at the beginning of my presentation.
I included just the relevant portion of my code.
' (2a)Adds Index Page, compiles file names into index page as a list
' Creates slide
Set oSld = ActivePresentation.Slides.Add(ActivePresentation.Slides.Count + 1, ppLayoutBlank)
With Application.ActivePresentation.PageSetup
.SlideHeight = 612
.SlideWidth = 1087
End With
' Create Title Box with Specified Dimensions and Slide Position
Set oPic = oSld.Shapes.AddShape(Type:=msoShapeRectangle, _
Left:=40, Top:=36, Width:=1007, Height:=540)
' FORMAT TEXTBOX SHAPE
' Shape Name
oPic.Name = "Index"
' No Shape Border
oPic.Line.Visible = msoFalse
' Shape Fill Color
oPic.Fill.ForeColor.RGB = RGB(255, 255, 255)
' Shape Text Color
oPic.TextFrame.TextRange.Font.Color.RGB = RGB(1, 0, 0)
' Left Align Text
oPic.TextFrame.TextRange.Paragraphs.ParagraphFormat.Alignment = ppAlignLeft
' Vertically Align Text to Top
oPic.TextFrame2.VerticalAnchor = msoAnchorTop
' Adjust Font Size
oPic.TextFrame2.TextRange.Font.Size = 11
' Adjust Font Style
oPic.TextFrame2.TextRange.Font.Name = "Arial"
' Change file path to desired directory and add "\" TO THE END:
strPath = "C:\Users\josephandrews\Desktop\Test\" '*****N.B. note the last "\" at end of line
strFileSpec = "*.jpg" 'you can change the selected file format, (e.g. "*.png") but only one file type can be used
strTemp = Dir(strPath & strFileSpec)
' Text inside Shape. Important to note that strTemp is the pic file name
oPic.TextFrame.TextRange.Characters.Text = strTemp & vbNewLine
' Required paramater for Loop through pictures
Do While strTemp <> ""
' Causes search for next picture in directory
strTemp = Dir
Loop
I expected this to create a list of all the file names in a text box.
It is only showing the name of the first file with a new line afterwards.

Found the answer. Here is my example.
Sub Test_2()
' Demonstrates the use of DIR to return a file at a time
Dim strPath As String
Dim strFile As String
Dim strFileSpec As String
Dim strFilesFound As String
Dim oSld As Slide
Dim oTbox As Shape
strPath = "C:\Users\BobComputer\Desktop\Test\" ' or wherever you want to look for files
strFileSpec = "*.jpg" ' or whatever type of files you want to list
' get the first file that meets our specification
strFile = Dir$(strPath & strFileSpec)
' if we got at least one file, continue:
While strFile <> ""
strFilesFound = strFilesFound & strFile & vbCrLf
' get the next file and loop
strFile = Dir
Wend
' let's see what we've got
'MsgBox strFilesFound
Set oSld = ActivePresentation.Slides(2)
Set oTbox = oSld.Shapes(1)
oTbox.TextFrame.TextRange.Characters.Text = strFilesFound
End Sub

Related

How to insert images as per slide title through vba code

I want to write VBA code for inserting the image as per the slide name from the folder means after running the VBA it automatically inserts the images as per the slide name
For eg: if the slide contains "Top View" in the text box then by running the VBA script it should automatically pick the picture having name "Top View" from the particular folder.
As shown in the attached images.
Slide having by text box as top view
Folder Path
I have posted one of the question some days ago but I didn't find the exact solution here is the link of my previous question which I have asked
Previous question
One of member has shared one code but its working properly also I modified it little bit though its not working properly if possible pl. help me
Option Explicit
Sub image_insert()
Dim objPresentaion As Presentation
Dim objSlide As Slide
Dim objImageBox As Shape
Dim sSlideTitle As String
Dim sFolder As String
Set objPresentaion = ActivePresentation
sFolder = "C:\Users\mehta\Desktop\Folder for ppt images\Top
View.jpg"
For Each objSlide In objPresentaion.Slides
sSlideTitle = GetTitleText(objSlide)
' WAS there a title on the slide?
If Len(sSlideTitle) > 0 Then
' make sure the image exists
If Len(Dir$(sFolder & sSlideTitle & ".JPG")) > 0 Then
Set objImageBox = objSlide.Shapes.AddPicture(sFolder &
sSlideTitle & ".JPG", _
msoCTrue, msoCTrue, 25, 25)
Else
' Comment this out later
' MsgBox "Image missing: " & sSlideTitle
End If
Else
' comment this out later:
MsgBox "This slide has no title"
End If
Next ' Slide
End Sub
Function GetTitleText(oSl As Slide) As String
Dim sTemp As String
With oSl
' handle errors in case there's no slide title
On Error Resume Next
sTemp = .Shapes.Title.TextFrame.TextRange.Text
If Err.Number <> 0 Then
sTemp = ""
End If
End With
GetTitleText = sTemp
End Function
Regards.

Error: -2147188160 Slides.Item: Integer out of range.2 is not in in index's valid range of 1 to 1 VBA power point error

I'm trying to extract few specific slide numbers from each ppt and trying to paste them into a single ppt using VBA.But Im facing this error.Im quite new to VBA ,so it would be of great help how to proceed further.
Tried with the suggestions given in the link https://support.microsoft.com/en-us/help/285472/run-time-error-2147188160-on-activewindow-or-activepresentation-call-i#:~:text=This%20behavior%20is%20caused%20by,code%20will%20cause%20this%20error.
But it is not working
Thanks in Advance
My code is as follows:
Sub sample()
Dim objPresentation As Presentation
On Error GoTo ErrorHandler
Dim sListFileName As String
Dim sListFilePath As String
Dim iListFileNum As Integer
Dim sBuf As String
' EDIT THESE AS NEEDED
' name of file containing files to be inserted
sListFileName = "LIST2.TXT"
' backslash terminated path to folder containing list file:
sListFilePath = "path"
' Do we have a file open already?
If Not Presentations.Count > 0 Then
Exit Sub
End If
' If LIST.TXT file doesn't exist, create it
If Len(Dir$(sListFilePath & sListFileName)) = 0 Then
iListFileNum = FreeFile()
Open sListFilePath & sListFileName For Output As iListFileNum
' get file names
sBuf = Dir$(sListFilePath & "*.PPT")
While Not sBuf = ""
Print #iListFileNum, sBuf
sBuf = Dir$
Wend
Close #iListFileNum
End If
iListFileNum = FreeFile()
Open sListFilePath & sListFileName For Input As iListFileNum
' Process the list
While Not EOF(iListFileNum)
' Get a line from the list file
Line Input #iListFileNum, sBuf
' Verify that the file named on the line exists
If Dir$(sBuf) <> "" Then
Dim SlideArray As Variant
'Set variable to Active Presentation
Set OldPPT = ActivePresentation
'Create a brand new PowerPoint presentation
If PowerPoint.Application.Version >= 9 Then
'window must be visible
PowerPoint.Application.Visible = msoTrue
End If
Set NewPPT = Presentations.Add
InSlides = InputBox("List the slide numbers separated by commas:", "Slides", 2)
SlideArray = Split(InSlides, ",")
For x = 0 To UBound(SlideArray)
sld = CInt(SlideArray(x))
'Set variable to a specific slide
Set Old_sld = OldPPT.Slides(sld)
'Copy Old Slide
y = Old_sld.SlideIndex
Old_sld.Copy
'Paste Slide in new PowerPoint
NewPPT.Slides.Paste
Set New_sld = Application.ActiveWindow.View.Slide
'Bring over slides design
New_sld.Design = Old_sld.Design
'Bring over slides custom color formatting
New_sld.ColorScheme = Old_sld.ColorScheme
'Bring over whether or not slide follows Master Slide Layout (True/False)
New_sld.FollowMasterBackground = Old_sld.FollowMasterBackground
Next x
End If
Wend
Close #iListFileNum
MsgBox "DONE!"
NormalExit:
Exit Sub
ErrorHandler:
Call MsgBox("Error:" & vbCrLf & Err.Number & vbCrLf & Err.Description, _
vbOKOnly, "Error inserting files")
Resume NormalExit
End Sub

Powerpoint VBA to insert image and change size

I think this could solve problems for a lot of people doing tedious pasting of images from one directory into powerpoint then resizing them.
My problem is that I have 16 images all in one directory which need updating each month and it's very slow to do it one by one. The task is:
Open directory
Open first image
Paste image into powerpoint
Reposition image to top left
Resize image to height 550 by width 960 (fills A4 page)
Send image to back
Move to next slide
Repeat for second image
Continue until no more images in directory
Directory is (e.g.) "C:\Users\xxxxxx\Documents\Work\Procurement Project\Slides"
First image name is (e.g.) "01 Summary", second is "02 Client Contracts" etc etc
I think I need a str and a path and a table for the str to add to path to create each new path using i and i + 1 etc
I think I then need some code that's a bit like this:
Sub Picture_size_and_position()
Dim oShape As Shape
Dim oPresentation As Presentation
Dim oSlide As Slide
Dim oSelection As Selection
ActiveWindow.View.GotoSlide oSlide.SlideIndex
With ActiveWindow.Selection.ShapeRange
.LockAspectRatio = msoFalse
.Height = 550
.Width = 960
.Left = 0
.Top = 0
End With
End Sub
Then I'm sure I need a looping function to repeat this until there's nothing left in the directory using some combination of i and j...but the whole code is way beyond me, very frustratingly.
Could someone offer some tips, please? Much much appreciated!
Thank you!
Sub ImportABunch()
Dim strTemp As String
Dim strPath As String
Dim strFileSpec As String
Dim oSld As Slide
Dim oPic As Shape
' Edit these to suit:
strPath = "C:\Users\username\"
strFileSpec = "*.png"
strTemp = Dir(strPath & strFileSpec)
i = 1
Do While strTemp <> ""
Set oSld = ActivePresentation.Slides(i)
Set oPic = oSld.Shapes.AddPicture(FileName:=strPath & strTemp, _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, _
Left:=0, _
Top:=0, _
Width:=960, _
Height:=550)
i = i + 1
With oPic
.LockAspectRatio = msoFalse
.ZOrder msoSendToBack
End With
' Or (with thanks to David Marcovitz) make the picture as big as possible on the slide
' without changing the proportions
' Leave the above commented out, uncomment this instead:
' With oPic
' If 3 * .width > 4 * .height Then
' .width = ActivePresentation.PageSetup.Slidewidth
' .Top = 0.5 * (ActivePresentation.PageSetup.Slideheight - .height)
' Else
' .height = ActivePresentation.PageSetup.Slideheight
' .Left = 0.5 * (ActivePresentation.PageSetup.Slidewidth - .width)
' End If
' End With
' Optionally, add the full path of the picture to the image as a tag:
'With oPic
' .Tags.Add "OriginalPath", strPath & strTemp
'End With
' Get the next file that meets the spec and go round again
strTemp = Dir
Loop
End Sub
Credit to http://www.pptfaq.com/index.html - Great little site!
Have an idea to automate it/or upon manual launch of a new Macro Enabled PowerPoint Template file. To automate macro upon file open, add customUI: onLoad="ImagesToPowerPoint". Search "CustomUI Editor" for it.
Note I have not fully tested the automation part.
Option Explicit
Sub ImagesToPowerPoint()
Const FileType As String = "*.png"
Dim sSaveFilePath As String, sSaveFileName As String, sImagesFolder As String
Dim oLayout As CustomLayout, oSlide As Slide, i As Long, sFile As String
sImagesFolder = Environ("USERPROFILE") & "\Documents\Work\Procurement Project\Slides\"
' Prepare auto save PowerPoint file name
sSaveFilePath = Environ("USERPROFILE") & "\Documents\Work\PowerPoints\"
sSaveFileName = Format(Now, "yyyy_mmdd") & "_Procurement.pptx"
With ActivePresentation
' Use the first layout for all new slides
Set oLayout = .SlideMaster.CustomLayouts(1)
' Start processing all files in the folder
sFile = Dir(sImagesFolder & FileType)
Do Until sFile = ""
' Add new slide
Set oSlide = .Slides.AddSlide(.Slides.Count, oLayout)
' Delete all the shapes from that layout
For i = oSlide.Shapes.Count To 1 Step -1
oSlide.Shapes(i).Delete
Next
' Add the image to slide
With oSlide.Shapes.AddPicture(sImagesFolder & sFile, msoFalse, msoTrue, 0, 0, oLayout.Width, oLayout.Height)
.LockAspectRatio = msoFalse
.AlternativeText = Now & " | " & sImagesFolder & sFile
End With
sFile = Dir
Loop
.SaveAs sSaveFilePath & sSaveFileName
End With
Presentations(sSaveFileName).Close
If Presentations.Count = 0 Then Application.Quit
End Sub

How can I import a text file into PowerPoint with vba?

I am used to doing this type of thing in Word, but the methods for the same sort of thing in PowerPoint are quite different.
I have a network folder with a list of text files in it. I want to be able to click into a text field on a slide and then click an import button on a custom menu. I then select one of the text files in the dialog and that imports the text into the area I have specified.
I have built the custom menu in PowerPoint 2010, and added a few other macros, but I can't work out the methods to use.
Can anyone give me a start?
Here is the code I am playing with:
Sub GetTextFromLibrary()
Dim lCurrentView As Long
Dim SlideNum As Integer
Dim Name$
Dim OldName$
'Store the default shape name to reset later
OldName$ = ActiveWindow.Selection.ShapeRange(1).Name
'Now rename the shape to work with it
Name$ = "temp01"
MsgBox "You are on slide: " & _
OldName$, vbInformation
ActiveWindow.Selection.ShapeRange(1).Name = Name$
' Get the current view type.
lCurrentView = ActiveWindow.ViewType
' Make sure that PowerPoint is in Slide view.
' ActiveWindow.Selection.SlideRange.SlideNumber produces an error if
' you are using any other view.
If lCurrentView = ppViewNormal Then
' Display the slide number.
'MsgBox "You are on slide: " & _
ActiveWindow.Selection.SlideRange.SlideNumber, vbInformation
SlideNum = ActiveWindow.Selection.SlideRange.SlideNumber
MsgBox "You are on slide: " & _
SlideNum, vbInformation
' Dim a variable as a specific object type
Dim oShape As Shape
' Set it to "point" to a specific shape:
Set oShape = ActivePresentation.Slides(SlideNum).Shapes("temp01")
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'Declare a variable for the directory path.
Dim directory As String
'Set the directory path
directory = "C:\Documents and Settings\<USER>\Desktop\PitchTemplateLibrary\Quotes"
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Declare a variable to contain the path
'of each selected item. Even though the path is aString,
'the variable must be a Variant because For Each...Next
'routines only work with Variants and Objects.
Dim vrtSelectedItem As Variant
'Use a With...End With block to reference the FileDialog object.
With fd
'Change the initial directory\filename
.InitialFileName = directory
'Use the Show method to display the File Picker dialog box and return the user's action.
'The user pressed the button.
If .Show = -1 Then
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
Dim fs As Object
Dim f As Object
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile(vrtSelectedItem, 1, 0)
' Put the text into the text box
oShape.TextFrame.TextRange.Text = f 'oShape IS EMPTY, BUT CAN"T SEE WHY.
Next vrtSelectedItem
'The user pressed Cancel.
Else
End If
End With
' Until we release the memory used by oShape
Set oShape = Nothing
ActiveWindow.Selection.ShapeRange(1).Name = OldName$
Else
' PowerPoint is not in slide view.
MsgBox "You must be in slide view to run this macro.", _
vbInformation
End If
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
PowerPoint code to set the text of a TextBox, or other Shape, is:
ActivePresentation.Slides(1).Shapes(3).TextFrame.TextRange _
= "Hello there"
I want to be able to click into a text field on a slide and then click an import button on a custom menu. I then select one of the text files in the dialog and that imports the text into the area I have specified.
' CYA
If Not ActiveWindow.Selection.Type = ppSelectionText Then
MsgBox "Select some text first"
Exit Sub
End if
' You might also want to allow for the case where the user has
' selected a rectangle or other shape rather than a text range.
' You could add the text to the shape as well.
With ActiveWindow.Selection.TextRange
.TextFrame.Text = "Text you've read from the chosen file"
End With

How to read lines from a text file one by one with Power Point VBA code?

This code will read a line from a text file:
set file = CreateObject("Scripting.FileSystemObject").OpenTextFile("c:\number.txt", 1)
text = file.ReadLine
MsgBox text
How can I make it read repeatedly one line after another from the same file? I guess, I should use a loop here, right? I need it to read the first line from the file at the first iteration, the second line at the second iteration, the third one at the third and so on till all the lines have been read. How can I do it?
Important addition: I need the code to operate on each line one by one - not all at once!
Use the ReadAll() method:
text = file.ReadAll
(Might be of interest: FileSystemObject Sample Code)
With a loop:
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, MyFile, FileName, TextLine
Set fso = CreateObject("Scripting.FileSystemObject")
FileName = "c:\testfile.txt"
Set MyFile = fso.OpenTextFile(FileName, ForReading)
'' Read from the file
Do While MyFile.AtEndOfStream <> True
TextLine = MyFile.ReadLine
'' Do stuff to TextLine
Loop
MyFile.Close
If for some reason you want to use the in-built VBA file handling routines, you would use code like this:
Sub ReadAFileLineByLine()
Dim InStream As Integer
InStream = FreeFile()
Open "C:/tmp/fastsynchtoquesttry_quest.txt" For Input As InStream
Dim CurrLine As String
Do While True
Line Input #InStream, CurrLine
' do stuff to CurrLine
If EOF(InStream) Then Exit Do
Loop
Close #InStream
End Sub
You can add a reference* to the Windows Script Host Object Model, it will help you with the FileSystemObject Object, because you can then say:
Dim fs As FileSystemObject
Dim f As TextStream
Which will allow you to use intellisense to see the various properties and the Object Browser to explore the library.
* In the code window, choose Tools, References and tick the box beside the library you want.
I wrote a VBA routine that reads a text file and insert a new slide for each sentence in the text.
First, in slide #1, add a button that calls the macro named "generate"
Source code goes:
Const DEFAULT_SLIDE = 1 ' the slide to copy the layout style from
Const MARGIN = 50 ' margin of the generated textbox
Sub generate()
Dim txtFile As String ' text file name
Dim fileNo As Integer ' file handle
Dim buffer As String ' temporary string buffer
Dim sentence() As String ' the main array to save sentences
Dim i, total As Integer
Dim myLayout As CustomLayout
Dim mySlide As Slide
Dim myShape As Shape
Dim myWidth, myHeight As Integer 'slide width and height
txtFile = "text2sample.txt"
txtFile = ActivePresentation.Path & "\" & txtFile 'textfile should be in the same Dir as this ppt
If Len(Dir$(txtFile)) = 0 Then
MsgBox txtFile & " file not found."
Exit Sub
End If
'Initialize array
ReDim sentence(0)
'get file handle number
fileNo = FreeFile()
Open txtFile For Input As #fileNo
i = 0
Do While Not EOF(fileNo)
Line Input #fileNo, buffer 'read & save sentences line by line
ReDim Preserve sentence(i + 1) ' increase 1 more array
sentence(i) = LTrim(RTrim(buffer))
i = i + 1
Loop
Close #fileNo
total = i
Randomize ' for random color
With ActivePresentation.PageSetup
myWidth = .SlideWidth - MARGIN 'get width and height
myHeight = .SlideHeight - MARGIN
End With
For i = 0 To total
Set myLayout = ActivePresentation.Slides(DEFAULT_SLIDE).CustomLayout
'add a slide like slide #1
Set mySlide = ActivePresentation.Slides.AddSlide(DEFAULT_SLIDE + 1 + i, myLayout)
'add a textbox with margin
Set myShape = ActivePresentation.Slides(DEFAULT_SLIDE + 1 + i).Shapes. _
AddTextbox(msoTextOrientationHorizontal, MARGIN, MARGIN, myWidth, myHeight)
With myShape
'add a sentence
.TextFrame.TextRange.Text = sentence(i)
.TextFrame.TextRange.Font.Size = 60
' color 255 is too bright. Pick a less bright color (200)
.TextFrame.TextRange.Font.Color.RGB = RGB(Int(Rnd * 200), Int(Rnd * 200), Int(Rnd * 200))
.TextFrame.TextRange.Font.Bold = msoTrue
.TextFrame.TextRange.Font.Shadow = msoTrue
' If you want to change the color of the shape
'.Fill.ForeColor.RGB = RGB(Int(Rnd * 200), Int(Rnd * 200), Int(Rnd * 200))
'.Fill.BackColor.RGB = RGB(Int(Rnd * 200), Int(Rnd * 200), Int(Rnd * 200))
'.Fill.Solid
End With
'add a textbox for slideshow progress ex) 1/100
Set myShape = ActivePresentation.Slides(DEFAULT_SLIDE + 1 + i).Shapes. _
AddTextbox(msoTextOrientationHorizontal, 0, 0, 150, 20)
With myShape
.TextFrame.TextRange.Text = "( " & i & " /" & total & " )"
.TextFrame.TextRange.Font.Size = 20
.TextFrame.TextRange.Font.Color.RGB = RGB(100, 100, 100)
End With
Next
MsgBox total & " Slides were added.", vbInformation
End Sub
Download file:
http://konahn.tistory.com/attachment/cfile8.uf#2175154C573D3BC02A2DFA.pptm