How can I import a text file into PowerPoint with vba? - 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

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.

Extract file names from directory into textbox Powerpoint 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

Open Excel from Word using FileDialog

What I want to do is:
Press a button in my Microsoft Word doc it will prompt me to select a document in the file explorer.
Select my document the relevant fields in my word doc will be populated.
This will be populated based upon information in the document (the month) and using a Match function it will search for the correct row/column in the selected excel document and return the value.
I am stuck on the FileDialog(msoFileDialogFilePicker) section of my code below.
For the purpose of my document I can not enter the direct file path, the file path needs to be taken from the FileDialog function (or something similar).
I have also tried GetOpenFilename. I am unsure how to do this. My code currently opens FileDialog and lets me select a file, but I can not pass the file path onto my colNum1 line.
The error I get is Run-time error '91'. Object variable or With Block variable not set.
I am open to suggestions and any help is much appreciated.
Sub KPI_Button()
'
' KPI_Button Macro
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim strFile As String
Dim Doc As String
Dim Res As Integer
Dim dlgSaveAs As FileDialog
Doc = ThisDocument.Name
Set dlgSaveAs = Application.FileDialog(msoFileDialogFilePicker)
Res = dlgSaveAs.Show
colNum1 = WorksheetFunction.Match("(Month)", ActiveWorkbook.Sheets("Sheet1").Range("A2:I2"), 0)
ThisDocument.hoursworkedMonth.Caption = exWb.Sheets("Sheet1").Cells(3, colNum1)
exWb.Close
Set exWb = Nothing
End Sub
try a dialog that specifies an Excel extension as such:
Sub GetNames()
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Excel files", "*.xls*", 1
If .Show = True Then
If .SelectedItems.Count > 0 Then
'this is the path you need
MsgBox .SelectedItems(1)
Else
MsgBox "no valid selection"
End If
End If
End With
End Sub

Copy the contents of a document(s) through FileDialogbox picker, to a new one

With MS_Word 2010 I have been trying to achieve the way to copy the contents(whole) of one file to a new one retrieving the file name of the original and adding it to the new one with the suffix "Copy".
All this process has a reason, since the Original document has only a few editable section and have protection enable (And I cant disable it) but I need to review it with other macro, so with a Copy of the contents in a new document I have been able to apply my whole macro. I also know of the method CopyFile but since this method copy also the characteristic of the original doc (the constrains in edit) I decide not to use it.
Searching around and using the recorder(for the copy actions) i have been able to come with this:
Sub Backup()
Dim DocName As String
Dim DocPath As String
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'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
'Allow the user to select multiple files.
.AllowMultiSelect = True
'Use the Show method to display the File Picker dialog box and return the user's action.
'If the user presses the button...
If .Show = -1 Then
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
On Error Resume Next
'vrtSelectedItem is aString that contains the path of each selected item. You can use any file I/O functions that you want to work with this path.
'MsgBox "Selected item's path: " & vrtSelectedItem
'Retrieve the name of the current doc (later I found out about .Name, .Path, .FullName ...)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
DocName = fso.GetBaseName(vrtSelectedItem)
'MsgBox "Selected item's : " & DocName
'Retrieve the path without the filename/extention
Documents.Open(vrtSelectedItem).Active
DocPath = ActiveDocument.Path
'MsgBox "Selected item's path: " & DocPath
'Copy the content of the current document
'With Documents(DocName)
With ActiveDocument
.WholeStory
.Copy
End With
'Create Backup File with ability to modify it, since the original is protected by password and only few segments are enable to edit
Documents.Add Template:=DocName & "Copy", NewTemplate:=False, DocumentType:=0
'Since Document.Add its suppose to promp as the Active document
'Paste the contents and save
'With Documents(DocName & "Copy")
With ActiveDocument
.PasteAndFormat (wdUseDestinationStylesRecovery)
.SaveAs DocPath
End With
'Documents(DocName & "Copy").Close SaveChanges:=True
Next
'If the user presses Cancel...
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
But as you guess, it doesn't work as desire and don't create the copy neither the new document with the name. So any scope in the right direction will be appreciate.
Thanks in advance for all the answers.
For future reference here is the code improved, based in the Response of #Charlie
Sub Backup()
Dim DocName As String
Dim NewDoc As Document
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'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
'Allow the user to select multiple files.
.AllowMultiSelect = True
'Use the Show method to display the File Picker dialog box and return the user's action.
'If the user presses the button...
If .Show = -1 Then
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
On Error Resume Next
'vrtSelectedItem is aString that contains the path of each selected item. You can use any file I/O functions that you want to work with this path.
'MsgBox "Selected item's path: " & vrtSelectedItem
'Retrieve the name of the current doc (later I found out about .Name, .Path, .FullName ...)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
DocName = fso.GetBaseName(vrtSelectedItem)
'MsgBox "Selected item's : " & DocName
'Create Backup File with ability to modify it, since the original is protected by password and only few segments are enable to edit
Set NewDoc = Documents.Add
'Since Document.Add its suppose to promp as the Active document
'Paste the contents and save
With NewDoc
Selection.InsertFile FileName:=vrtSelectedItem, Range:=vbNullString, _
ConfirmConversions:=False, Link:=False, Attachment:=False
.SaveAs FileName:=vrtSelectedItem & "_BACKUP.docx"
.Close
End With
Next
'If the user presses Cancel...
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
I would try creating a new Word doc then using this line to "insert the text from the protected Word doc." It's the same as going to the Insert Ribbon tab -> Object -> Text from File.
Selection.InsertFile FileName:="protected.docx", Range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False

Open PowerPoint from directory and resume macro

I'm trying to open a PPTX from a specific folder using a Function within a Sub. The function's purpose is to choose the file that the rest of the macro's code will perform it on (essentially to make it the ActivePresentation) The problem is that when I call the function PickDir() to get the file's path and open it, the macro stops running. So, I just get an open presentation and not performing the action I want it to do.
The problem occurs about 5 lines after all the variables are Dim'd.
Sub ExtractImagesFromPres()
On Error GoTo ErrorExtract
Dim oSldSource As Slide
Dim oShpSource As Shape
Dim ImgCtr As Integer
Dim SldCtr As Integer
Dim ShapeNameArray() As String
Dim oPP As Object
Dim SrcDir As String
Dim SrcFile As String
'File naming variables
Dim PPLongLanguageCode As String
Dim PPShortLanguageCode As String
Dim FNShort As String
Dim FNLong As String
Dim PPLanguageParts1() As String
Dim PPLanguageParts2() As String
Dim FNLanguageParts() As String
SrcDir = PickDir() 'call the PickDir() function to choose a directory to work from
If SrcDir = "" Then Exit Sub
SrcFile = SrcDir & "\" & Dir(SrcDir + "\*.pptx") 'complete directory path of ppt to be split
Set oPP = CreateObject("Powerpoint.Application") 'open ppt containing slides with images/text to be exported
ActivePresentation = oPP.Presentations.Open(SrcFile, False, False, True)
ImgCtr = 0 'Image and Slide counter for error messages
SldCtr = 1
ReDim ShapeNameArray(1 To 1) As String 'initialize ShapeNameArray to avoid null array errors
For Each oSldSource In ActivePresentation.Slides
For Each oShpSource In oSldSource.Shapes 'loop each shape within each slide
If oShpSource.Type <> msoPlaceholder Then 'if shape is not filename placeholder then add it's name to ShapeNameArray
ShapeNameArray(UBound(ShapeNameArray)) = oShpSource.Name
ReDim Preserve ShapeNameArray(1 To UBound(ShapeNameArray) + 1) As String 'need to add one to array for new shape name
ElseIf oShpSource.Type = msoPlaceholder Then 'is shape is filename placeholder then check to see if not empty
If oShpSource.TextFrame.TextRange.Length = 0 Then
MsgBox "The filename is missing on Slide:" & SldCtr & vbNewLine & _
"Please enter the correct filname and re-run this macro"
Exit Sub
End If
PPLanguageParts1 = Split(ActivePresentation.Name, ".") 'extract language code from PowerPoint filename
PPLongLanguageCode = PPLanguageParts1(LBound(PPLanguageParts1))
PPLanguageParts2 = Split(PPLongLanguageCode, "_")
PPShortLanguageCode = PPLanguageParts2(UBound(PPLanguageParts2))
FNLanguageParts = Split(oShpSource.TextFrame.TextRange.Text, "_") 'insert PowerPoint filename language code into image filename language code
FNShort = FNLanguageParts(LBound(FNLanguageParts))
FNLong = FNShort & "_" & PPShortLanguageCode
oShpSource.TextFrame.TextRange.Text = FNLong
End If
Next oShpSource
ReDim Preserve ShapeNameArray(1 To UBound(ShapeNameArray) - 1) As String 'ShapeNameArray has one too many elements, so subtract one
Call oSldSource.Shapes.Range(ShapeNameArray).Export(FNLong & ".jpg", ppShapeFormatJPG) 'export images with proper filenames
ReDim ShapeNameArray(1 To 1) As String
ImgCtr = ImgCtr + 1
SldCtr = SldCtr + 1
Next oSldSource
If ImgCtr = 0 Then 'error message if no images
MsgBox "There were no images found in this presentation", _
vbInformation, "Image extraction failed."
End If
Exit Sub
ErrorExtract:
If Err.Number <> 0 Then 'error message log
MsgBox Err.Description, vbCritical, "Error #" & Err.Number
End If
End Sub
Private Function PickDir() As String
Dim FD As FileDialog
PickDir = ""
Set FD = Application.FileDialog(msoFileDialogFolderPicker) 'initialize default MS directory picker
With FD
.Title = "Pick the folder where your files are located" 'title for directory picker dialog box
.AllowMultiSelect = False
.Show
If .SelectedItems.Count <> 0 Then
PickDir = .SelectedItems(1)
End If
End With
Are you running this from within powerpoint? If yes, you don't need to create another Application object: you can just open the ppt directly. And you can use the return value from Open() to get a reference to the presentation (rather than using "activePresentation")
Dim ppt as Presentation
Set ppt = Application.Presentations.Open(SrcFile, False, False, True)
'do stuff with ppt
This line is probably giving you some trouble:
ActivePresentation = oPP.Presentations.Open(SrcFile, False, False, True)
I don't know how to activate a window in PPT but at the very least you'll need to use the following:
Set ActivePresentation = oPP.Presentations.Open(SrcFile, False, False, True)
As for activating the presentation, you may need to access the windows collection, or something similar? A suggestion, hopefully to get you thinking.
application.Presentations(1).Windows(1).Activate
Finally, you may actually not need to activate the presentation, if you have no other presentations open, the one you're opening will quite likely be the active one by default, if you open it visible. I suspect this is the case, given that you are creating the powerpoint application object. If this is correct then you simply need to do the following:
oPP.Presentations.Open(SrcFile, False, False, True)
debug.print oPP.ActivePresentation.Name
Edit: I'd also recommend setting a reference to the powerpoint object library and declaring oPP as follows:
Dim oPP as Powerpoint.Application
Then when creating an instance of the application:
Set oPP = New Powerpoint.Application
If you don't want to have to worry about which presentation is active, you can do:
Dim oPres as Presentation
Set oPres = oPP.Presentations.Open(SrcFile, False, False, True)
Then in the rest of the code, use oPres instead of ActivePresentation