I have below macro that brings file from saved file from excel to PowerPoint what I need is to update the macro to bring one file per slide instead of bringing all into one slide
Sub CreatePagePerComment()
Dim PowerPointApp As Object
Dim myPPTX As Object
Dim mySlide As Object
Dim pptxNm As String
Dim pptNm As Range
Dim rSht As Worksheet
Dim oSht As Worksheet
Dim oPicture As Object
Set pptNm = ThisWorkbook.Sheets("Sheet1").[PPTX_File]
Sheets("Sheet1").[PPTX_File].Value = pptNm.Value
CONFIRM_PPTX_APP:
'Create an Instance of PowerPoint
On Error Resume Next
'Is PowerPoint already opened?
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
Err.Clear
'If PowerPoint is not already open then open PowerPoint
If PowerPointApp Is Nothing Then
'Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
With pptNm.Validation
.Delete 'delete previous validation
End With
MsgBox "No PowerPoint file is open. Please open the PowerPoint file to where you " & _
"would like to export this table.", vbOKOnly + vbCritical, ThisWorkbook.Name
Exit Sub
End If
'Handle if the PowerPoint Application is not found
If Err.Number = 429 Then
MsgBox "PowerPoint could not be found, aborting."
Exit Sub
End If
On Error GoTo 0
GET_PPTX_FILENAME:
If pptNm.Value = "" Then
MsgBox "Please select the PowerPoint file name, from the drop down list, to where you want to export the Headcount Review summary table." & _
Chr(10) & Chr(10) & "This Macro has selected the cell that contains a list of all open PowerPoint files. " & Chr(10) & Chr(10) & _
"If your file is not listed, please confirm it is open, then select any other cell, then return to this cell for " & _
"a refreshed file name list.", vbOKOnly + vbCritical, "No PowerPoint File Selected"
pptNm.Select
Exit Sub
Else:
If InStr(1, pptNm.Value, "ppt") > 0 Then
pptxNm = pptNm.Value
ElseIf InStr(1, pptNm.Value, "pptx") > 0 Then
pptxNm = pptNm.Value & ".pptx"
ElseIf InStr(1, pptNm.Value, "pptm") > 0 Then
pptxNm = pptNm.Value & ".pptm"
End If
End If
pptxNm = "NN Commitment Cards.pptm"
Set myPPTX = PowerPointApp.Presentations(pptxNm)
PowerPointApp.Visible = True
PowerPointApp.Activate
'Adds second slide
'MsgBox SlideShowWindows(1).View.Slide.SlideIndex
Dim Nm_shp As Shape, sld_no As Integer
Dim pIndex As Integer, pName As String
sld_no = myPPTX.Slides.Count
pName = "Blue Transition"
pIndex = 3
ADD_NEW_SLIDE:
Dim SlideCnt As Integer
Set mySlide = myPPTX.Slides.Add(sld_no + 1, 12)
mySlide.Select
mySlide.CustomLayout = myPPTX.Designs("N_PPTX_Theme").SlideMaster.CustomLayouts(pIndex)
'mySlide.Shapes.AddOLEObject Left:=10, Top:=10, Width:=(7.5 * 72), Height:=(10 * 72),
' Filename:=[B1].Value & "\" & [A132].Value & ".pdf", displayasicon:=msoFalse, link:=msoTrue
For Each cel In [A3:A4]
If Cells(cel.Row, [A1].Column).Value <> "" Then
Set oPicture = mySlide.Shapes.AddPicture([B1].Value & "\" & cel.Value & ".png", _
msoFalse, msoTrue, Left:=10, Top:=10, Width:=(6 * 72), Height:=(7 * 72))
Set oSlide = myPPTX.Slides(1)
With oPicture
.Width = 7 * 72
.Height = 8 * 72
.PictureFormat.CropLeft = 0
.PictureFormat.CropTop = 0
.PictureFormat.CropRight = 0
.PictureFormat.CropBottom = oPicture.Height / 1.85
.Name = cel.Value
.Line.Weight = 0.5
.Line.Visible = msoTrue
.LockAspectRatio = msoTrue
.Left = 1.5 * 72
.Top = 1.5 * 72
With myPPTX.PageSetup
oPicture.Left = (.SlideWidth \ 2) - (oPicture.Width \ 2)
oPicture.Top = (.SlideHeight \ 2) - (oPicture.Height \ 2)
End With
End With
End If
End Sub
What is the required tweak that I need to update in this macro to do so?
I am assuming the rest of your code is working and focusing only on your specific question. First, there is no reference to oSlide in your code, so I assume that's some typo. From my reading of your code, you add a new slide to the current slide and add a picture to it (or not since that section of code is commented out). Then, based on the content of [A3:A4], you want to add new slides, each with a new picture. I have discarded commented code and kept your code as unmodified as possible in providing this solution (change the required section fo your code):
'Adds second slide
'MsgBox SlideShowWindows(1).View.Slide.SlideIndex
Dim Nm_shp As Shape, sld_no As Integer
Dim pIndex As Integer, pName As String
sld_no = myPPTX.Slides.Count
pName = "Blue Transition"
pIndex = 3
ADD_NEW_SLIDE:
Dim SlideCnt As Integer
SlidCnt = 0
For Each cel In [A3:A4]
If Cells(cel.Row, [A1].Column).Value <> "" Then
SlideCnt = SlideCnt + 1
Set mySlide = myPPTX.Slides.Add(sld_no + SlideCnt, 12)
mySlide.CustomLayout = myPPTX.Designs("N_PPTX_Theme").SlideMaster.CustomLayouts(pIndex)
Set oPicture = mySlide.Shapes.AddPicture([B1].Value & "\" & cel.Value & ".png", _
msoFalse, msoTrue, Left:=10, Top:=10, Width:=(6 * 72), Height:=(7 * 72))
With oPicture
.Width = 7 * 72
.Height = 8 * 72
.PictureFormat.CropLeft = 0
.PictureFormat.CropTop = 0
.PictureFormat.CropRight = 0
.PictureFormat.CropBottom = oPicture.Height / 1.85
.Name = cel.Value
.Line.Weight = 0.5
.Line.Visible = msoTrue
.LockAspectRatio = msoTrue
.Left = 1.5 * 72
.Top = 1.5 * 72
With myPPTX.PageSetup
oPicture.Left = (.SlideWidth \ 2) - (oPicture.Width \ 2)
oPicture.Top = (.SlideHeight \ 2) - (oPicture.Height \ 2)
End With
End With
End If
Next cel
Related
when trying to import and resize cells and pics on mass upto 200 for example. i need to save the images and not just a link to them so i can email xls to someone else who wont have the images or files store on there computer.
Sub AddOlEObject()
Dim mainWorkBook As Workbook
Application.ScreenUpdating = False
Set mainWorkBook = ActiveWorkbook
Sheets("Object").Activate
where you want your pictures to go
Folderpath = "folder path"
Set fso = CreateObject("Scripting.FileSystemObject")
NoOfFiles = fso.GetFolder(Folderpath).Files.Count
Set listfiles = fso.GetFolder(Folderpath).Files
For Each fls In listfiles
strCompFilePath = Folderpath & "\" & Trim(fls.Name)
If strCompFilePath <> "" Then
If (InStr(1, strCompFilePath, "jpg", vbTextCompare) > 1 _
Or InStr(1, strCompFilePath, "jpg", vbTextCompare) > 1 _
Or InStr(1, strCompFilePath, "jpg", vbTextCompare) > 1) Then
counter = counter + 1
Sheets("Object").Range("A" & counter).Value = fls.Name
Sheets("Object").Range("B" & counter).ColumnWidth = 60 'Adjust to fit your pictures
Sheets("Object").Range("B" & counter).RowHeight = 70 'Adjust to fit your pictures
Sheets("Object").Range("B" & counter).Activate
Call insert(strCompFilePath, counter)
Sheets("Object").Activate
End If
End If
Next
mainWorkBook.Save
Application.ScreenUpdating = True
End Sub
Function insert(PicPath, counter)
'MsgBox PicPath
With ActiveSheet.Pictures.insert(PicPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 30 'Adjust to change the WIDTH of your pictures
.Height = 70 'Adjust to change the HEIGHT of your pictures
End With
.Left = ActiveSheet.Range("B" & counter).Left
.Top = ActiveSheet.Range("B" & counter).Top
.Placement = 1
.PrintObject = True
End With
End Function
I have code which inserts images from the given path using specific set of numbers against which I already have an image database.
Sub InsertPics()
Dim fPath As String, fName As String
Dim r As Range, rng As Range
Dim shpPic As Shape
Application.ScreenUpdating = False
fPath = "C:\Users\DELL\Documents\FY18-19\Images\"
Set rng = Range("D2:D" & Cells(Rows.Count, 4).End(xlUp).Row)
For Each r In rng
On Error GoTo errHandler
If r.Value <> "" Then
Set shpPic = ActiveSheet.Shapes.AddPicture(Filename:=fPath & r.Value & ".jpg", linktofile:=msoFalse, _
savewithdocument:=msoTrue, Left:=Cells(r.Row, 2).Left, Top:=Cells(r.Row, 2).Top, Width:=-1, Height:=-1)
With shpPic
.LockAspectRatio = msoTrue
If .Width > Columns(2).Width Then .Width = Columns(2).Width
Rows(r.Row).RowHeight = .Height
End With
End If
errHandler:
If Err.Number <> 0 Then
Debug.Print Err.Number & ", " & Err.Description & ", " & r.Value
On Error GoTo -1
End If
Next r
Application.ScreenUpdating = True
End Sub
I need to do the below as well:
ask the file path
ask whether to insert the image as image or as a comment against those set of numbers and run accordingly
If the code can be converted into a select mode run, i.e. on a set of numbers I can run the code for (instead of the entire 'D'-Column I've embedded currently).
May try this code and modify to your requirement.
Sub InsertPics()
Dim fPath As String, fName As String
Dim r As Range, rng As Range
Dim shpPic As Shape, IsCmnt As VbMsgBoxResult
'Application.ScreenUpdating = False
Set rng = ThisWorkbook.ActiveSheet.Range("D2:D" & Cells(Rows.Count, 4).End(xlUp).Row)
On Error GoTo Xexit
Set rng = Application.InputBox("Select the range to import Images", "Import Image", rng.Address, , , , , 8)
On Error GoTo 0
If rng Is Nothing Then Exit Sub
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = " Select Folder to Upload Images"
.AllowMultiSelect = False
.InitialFileName = "C:\Users\user\DeskTop\"
If .Show <> -1 Then Exit Sub
fPath = .SelectedItems(1)
End With
fPath = fPath & "\"
'Avoided further asking wheather all Images are to be uploaded as Comment
'instead used bold font of the file names to do the same
'try Next statement, if want all the images as comment
'IsCmnt = MsgBox("Is the images to be uploaded as comments", vbYesNo)
For Each r In rng
If r.Value <> "" Then
If Dir(fPath & r.Value & ".jpg") <> "" Then
'If IsCmnt = vbYes Then 'try this branch if want all the images as comment
If r.Font.Bold Then ' instead of asking multiple times
r.ClearComments
r.AddComment ""
r.Comment.Shape.Fill.UserPicture fPath & r.Value & ".jpg"
Else
Set shpPic = ActiveSheet.Shapes.AddPicture(Filename:=fPath & r.Value & ".jpg", linktofile:=msoFalse, _
savewithdocument:=msoTrue, Left:=Cells(r.Row, 2).Left, Top:=Cells(r.Row, 2).Top, Width:=-1, Height:=-1)
With shpPic
.LockAspectRatio = msoTrue
If .Width > Columns(2).Width Then .Width = Columns(2).Width
Rows(r.Row).RowHeight = .Height
End With
End If
Else
Debug.Print fPath & r.Value & ".jpg not found"
End If
End If
Next r
Xexit:
'Application.ScreenUpdating = True
End Sub
Code is tested with makeshift images. May disable ScreenUpdatingas per actual condition.
Thanks to Macromarc This Problem has been resolved
The problem i had with my code was it was only putting in the picture to a cell, and the picture was sized incorrectly. When i filtered my data the pictures always collapsed into each other and it did not look too great.
Below is the correct code that will work for you thanks to Macromarc
Private Sub GrabImagePasteIntoCell()
Const pictureNameColumn As String = "A" 'column where picture name is found
Const picturePasteColumn As String = "J" 'column where picture is to be pasted
Const pathForPicture As String = "M:\Users\Dan\Pictures\LabPics\" 'path of pictures
Dim pictureFile As String
Dim pictureName As String 'picture name
Dim lastPictureRow As Long 'last row in use where picture names are
Dim pictureRow As Long 'current picture row to be processed
Dim picturePasteCell As Range
pictureRow = 3 'starts from this row
On Error GoTo Err_Handler
Dim ws As Worksheet
Set ws = ActiveSheet 'replace with better qualification
lastPictureRow = ws.Cells(ws.Rows.Count, pictureNameColumn).End(xlUp).Row
'stop screen updates while macro is running
Application.ScreenUpdating = False
'loop till last picture row
Do While (pictureRow <= lastPictureRow)
pictureName = ws.Cells(pictureRow, pictureNameColumn).Value2
If (pictureName <> vbNullString) Then
'check if pic is present
pictureFile = pathForPicture & pictureName
Set picturePasteCell = ws.Cells(pictureRow, picturePasteColumn)
If (Dir(pictureFile & ".jpg") <> vbNullString) Then
insertPictureToComment pictureFile & ".jpg", picturePasteCell, 41, 41
ElseIf (Dir(pictureFile & ".png") <> vbNullString) Then
insertPictureToComment pictureFile & ".png", picturePasteCell, 100, 130
ElseIf (Dir(pictureFile & ".bmp") <> vbNullString) Then
insertPictureToComment pictureFile & ".bmp", picturePasteCell, 100, 130
Else
'picture name was there, but no such picture
picturePasteCell.Value2 = "No Picture Found"
End If
Else
'picture name cell was blank
End If
pictureRow = pictureRow + 1
Loop
On Error GoTo 0
Exit_Sub:
ws.Range("A10").Select
Application.ScreenUpdating = True
Exit Sub
Err_Handler:
MsgBox "Error encountered. " & Err.Description, vbCritical, "Error"
GoTo Exit_Sub
End Sub
The function below handles the insertion of generic images to a cell's comment shape:
Function insertPictureToComment(pictureFilePath As String, _
pictureRange As Range, _
commentHeight As Long, _
commentWidth As Long)
Dim picComment As Comment
If pictureRange.Comment Is Nothing Then
Set picComment = pictureRange.AddComment
Else
Set picComment = pictureRange.Comment
End If
With picComment.Shape
.Height = commentHeight
.Width = commentWidth
.LockAspectRatio = msoFalse
.Fill.UserPicture pictureFilePath
End With
End Function
I rewrote some of the other code, and refactored out a function.
Tested and it is basically working for me. Any questions ask:
Private Sub GrabImagePasteIntoCell()
Const pictureNameColumn As String = "A" 'column where picture name is found
Const picturePasteColumn As String = "J" 'column where picture is to be pasted
Const pathForPicture As String = "M:\Users\Dan\Pictures\LabPics\" 'path of pictures
Dim pictureFile As String
Dim pictureName As String 'picture name
Dim lastPictureRow As Long 'last row in use where picture names are
Dim pictureRow As Long 'current picture row to be processed
Dim picturePasteCell As Range
pictureRow = 3 'starts from this row
On Error GoTo Err_Handler
Dim ws As Worksheet
Set ws = ActiveSheet 'replace with better qualification
lastPictureRow = ws.Cells(ws.Rows.Count, pictureNameColumn).End(xlUp).Row
'stop screen updates while macro is running
Application.ScreenUpdating = False
'loop till last picture row
Do While (pictureRow <= lastPictureRow)
pictureName = ws.Cells(pictureRow, pictureNameColumn).Value2
If (pictureName <> vbNullString) Then
'check if pic is present
pictureFile = pathForPicture & pictureName
Set picturePasteCell = ws.Cells(pictureRow, picturePasteColumn)
If (Dir(pictureFile & ".jpg") <> vbNullString) Then
insertPictureToComment pictureFile & ".jpg", picturePasteCell, 41, 41
ElseIf (Dir(pictureFile & ".png") <> vbNullString) Then
insertPictureToComment pictureFile & ".png", picturePasteCell, 100, 130
ElseIf (Dir(pictureFile & ".bmp") <> vbNullString) Then
insertPictureToComment pictureFile & ".bmp", picturePasteCell, 100, 130
Else
'picture name was there, but no such picture
picturePasteCell.Value2 = "No Picture Found"
End If
Else
'picture name cell was blank
End If
pictureRow = pictureRow + 1
Loop
On Error GoTo 0
Exit_Sub:
ws.Range("A10").Select
Application.ScreenUpdating = True
Exit Sub
Err_Handler:
MsgBox "Error encountered. " & Err.Description, vbCritical, "Error"
GoTo Exit_Sub
End Sub
The function below handles the insertion of generic images to a cell's comment shape:
Function insertPictureToComment(pictureFilePath As String, _
pictureRange As Range, _
commentHeight As Long, _
commentWidth As Long)
Dim picComment As Comment
If pictureRange.Comment Is Nothing Then
Set picComment = pictureRange.AddComment
Else
Set picComment = pictureRange.Comment
End If
With picComment.Shape
.Height = commentHeight
.Width = commentWidth
.LockAspectRatio = msoFalse
.Fill.UserPicture pictureFilePath
End With
End Function
I have never coded an application directly from Access, but it has been proving to be annoying. Every time I click on the button cmdChart nothing happens. I am not sure if there are any errors with the code. Access has no real syntax highlighting or error messages if something is wrong, so any input would be appreciated.
Here is the code I'm currently trying:
Private Sub cmdChart_Click()
On Error GoTo SubError
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim SQL As String
Dim rs1 As DAO.Recordset
Dim i As Integer
Dim qtr As String
Dim yr As String
Dim xlChart As Excel.ChartObject
Dim rng As Range
'Show user work is being performed
DoCmd.Hourglass (True)
'*********************************************
' RETRIEVE DATA
'*********************************************
'SQL statement to retrieve data from database
SQL = "SELECT 'Completed' AS Status, Count(tblPMWOs.PMWOID) AS CountOfPMWOID " & _
"From tblPMWOs " & _
"WHERE (([tblPMWOs].[DateComplete] >= DateAdd('m',-10,DateValue(#[#DailyReportStartDate]#))) AND ([tblPMWOs].[DateComplete] < DateAdd('d',1,DateValue(#[#DailyReportEndDate]#)))) " & _
"UNION ALL " & _
"SELECT 'Open' AS Status, Count(tblPMWOs.PMWOID) AS CountOfPMWOID " & _
"From tblPMWOs " & _
"WHERE (((tblPMWOs.DateGenerated) < #[#DailyReportEndDate]#) And ((tblPMWOs.DateComplete) >= #[#DailyReportEndDate]# Or (tblPMWOs.DateComplete) Is Null)) " & _
"Group BY 'Open' "
'Execute query and populate recordset
Set rs1 = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)
'If no data, don't bother opening Excel, just quit
If rs1.RecordCount = 0 Then
MsgBox "No data selected for export", vbInformation + vbOKOnly, "No data exported"
GoTo SubExit
End If
'*********************************************
' BUILD SPREADSHEET
'*********************************************
'Create an instance of Excel and start building a spreadsheet
'Early Binding
Set xlApp = Excel.Application
xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)
With xlSheet
.Cells.Font.Name = "Calibri"
.Cells.Font.Size = 11
'Set column widths
.Columns("B").ColumnWidth = 10
.Columns("C").ColumnWidth = 11
.Columns("D").ColumnWidth = 15
.Columns("E").ColumnWidth = 15
.Columns("F").ColumnWidth = 10
'Format columns
.Columns("D").NumberFormat = "$#,##0.00;-$#,##0.00"
.Columns("E").NumberFormat = "$#,##0.00;-$#,##0.00"
'Build values for second graph title - pull quarter and year off of first row
'Won't work if you are pulling multiple time periods!
Select Case Nz(rs1!SalesQuarter, "")
Case 1
qtr = "1st"
Case 2
qtr = "2nd"
Case 3
qtr = "3rd"
Case 4
qtr = "4th"
Case Else
qtr = "???"
End Select
yr = Nz(rs1!SalesYear, Year(Date))
'Column headings for the data grid
.Range("C22").Value = "Division"
.Range("D22").Value = "Gross Sales"
.Range("E22").Value = "Gross Margin"
.Range("C22:E22").HorizontalAlignment = xlCenter
.Range("C22:E22").Cells.Font.Bold = True
.Range("C22:E22").Cells.Font.Color = RGB(15, 36, 62)
.Range("C22:E22").Interior.Color = RGB(141, 180, 226)
'provide initial value to row counter
i = 23
'Loop through recordset and copy data from recordset to sheet
Do While Not rs1.EOF
.Range("C" & i).Value = Nz(rs1!Division, "")
.Range("D" & i).Value = Nz(rs1!GrossSales, 0)
.Range("E" & i).Value = Nz(rs1!GrossMargin, 0)
i = i + 1
rs1.MoveNext
Loop
.Range("C23:E" & i - 1).Interior.Color = RGB(220, 230, 241)
.Range("C23:E" & i - 1).Cells.Font.Color = RGB(22, 54, 92)
'grid-lines for data grid
.Range("C22:E22").Borders(xlEdgeTop).LineStyle = XlLineStyle.xlContinuous
.Range("C22:E22").Borders(xlEdgeTop).Color = RGB(22, 54, 92)
.Range("C22:C" & i - 1).Borders(xlEdgeLeft).LineStyle = XlLineStyle.xlContinuous
.Range("C22:C" & i - 1).Borders(xlEdgeLeft).Color = RGB(22, 54, 92)
.Range("E22:E" & i - 1).Borders(xlEdgeRight).LineStyle = XlLineStyle.xlContinuous
.Range("E22:E" & i - 1).Borders(xlEdgeRight).Color = RGB(22, 54, 92)
.Range("C22:E" & i - 1).Borders(xlInsideVertical).LineStyle = XlLineStyle.xlContinuous
.Range("C22:E" & i - 1).Borders(xlInsideVertical).Color = RGB(22, 54, 92)
.Range("C22:E" & i - 1).Borders(xlInsideHorizontal).LineStyle = XlLineStyle.xlContinuous
.Range("C22:E" & i - 1).Borders(xlInsideHorizontal).Color = RGB(22, 54, 92)
.Range("C" & i - 1 & ":E" & i - 1).Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
.Range("C" & i - 1 & ":E" & i - 1).Borders(xlEdgeBottom).Color = RGB(22, 54, 92)
'Create the chart
'(left, top, width, height) / 72 points per inch
Set xlChart = .ChartObjects.Add(50, 20, 338, 273)
With xlChart
.RoundedCorners = True
With .Chart
.chartType = xlColumnClustered
.HasTitle = True
With .ChartTitle
.Text = "Gross Sales and Gross Margin" & _
vbCr & qtr & " Quarter " & yr
With .Font
.Name = "Calibri"
.FontStyle = "Bold"
.Size = 14
End With 'end Font
End With 'end .ChartTitle
.HasLegend = True
.Legend.Position = xlLegendPositionBottom
'Method 1: Easy
'.SetSourceData Source:=xlSheet.Range("C22:E" & i - 1)
'Method 2: more control
.SeriesCollection.NewSeries
.SeriesCollection(1).Name = xlSheet.Range("D22")
.SeriesCollection(1).Values = xlSheet.Range("D23:D" & i - 1)
.SeriesCollection(1).XValues = xlSheet.Range("C23:C" & i - 1)
.SeriesCollection.NewSeries
.SeriesCollection(2).Name = xlSheet.Range("E22")
.SeriesCollection(2).Values = xlSheet.Range("E23:E" & i - 1)
.SeriesCollection(2).XValues = xlSheet.Range("C23:C" & i - 1)
.Axes(xlCategory).HasTitle = True
.Axes(xlCategory).AxisTitle.Caption = "Divisions"
'(xlCategory = x-axis, xlValue = y-axis)
End With 'end .Chart
End With 'end xlChart
End With
SubExit:
On Error Resume Next
DoCmd.Hourglass False
xlApp.Visible = True
rs1.Close
Set rs1 = Nothing
Exit Sub
SubError:
MsgBox "Error Number: " & Err.Number & "= " & Err.Description, vbCritical + vbOKOnly, _
"An error occurred"
GoTo SubExit
End Sub
My button OnClick property changed somehow. I just needed to change it to Event Procedure.
How to add image to specific named placeholder using VBA in Powerpoint (from Excel)
I've been trying to figure this one out for a while.
I've copied all my code below. What I am try to do I add 3 images to a Powerpoint in a format that I was provided.
The problem I experience, is that, when an imge isn't found (I've told the system to resume), the next image appears in the previous Placeholder. Not in the one I want it to.
The PowerPoint is Open, and as you can see, I've even tried selecting the placeholder to see if that makes a difference.
If there isn't a work around for this. Can anyone suggest how to capture that an Image didn't populate, so I can populate with an image that says "Image not available" Just to keep everything in the right place?
Search below for : If oPPtShp.PlaceholderFormat.Type = ppPlaceholderPicture Then
to find the start of the IF where I load in the images.
Please help!
Sub AddPPT2010()
On Error Resume Next
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Program Files (x86)\Microsoft Office\Office14\MSPPT.OLB"
Const imgFileName = "PrintIcon"
Const GUIDRef = "{91493440-5A91-11CF-8700-00AA0060263B}"
Set PrntIcon = Application.CommandBars.FindControl(ID:=4)
On Error Resume Next 'Ignore Error If Reference Already Established
ThisWorkbook.VBProject.References.AddFromGuid GUIDRef, 2, 10
On Error Resume Next
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Program Files (x86)\Microsoft Office\Office14\MSPPT.OLB"
Call addPPT2000
Call CreateSlides
MsgBox "Powerpoint Presentation build complete.", vbOKOnly
End Sub
Sub addPPT2000()
On Error Resume Next
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Program Files (x86)\Microsoft Office\Office14\MSPPT.OLB"
Const imgFileName = "PrintIcon"
Const GUIDRef = "{91493440-5A91-11CF-8700-00AA0060263B}"
Set PrntIcon = Application.CommandBars.FindControl(ID:=4)
On Error Resume Next 'Ignore Error If Reference Already Established
ThisWorkbook.VBProject.References.AddFromGuid GUIDRef, 2, 7
On Error Resume Next
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Program Files (x86)\Microsoft Office\Office14\MSPPT.OLB"
End Sub
Sub CreateSlides()
'Dim the Excel objects
Dim objWorkbook As New Excel.Workbook
Dim objWorksheet As Excel.Worksheet
'Dim the File Path String
Dim strFilePath As String
'Dim the PowerPoint objects
Dim PPT As Object
Dim pptSlide As PowerPoint.Slide
Dim pptLayout As PowerPoint.CustomLayout
Dim pptNewSlide As PowerPoint.Slide
Dim str As String
Dim Title As String
Dim oPPtShp As PowerPoint.Shape
Set PPT = GetObject(, "PowerPoint.Application")
PPT.Visible = True
'Get the layout of the first slide and set a CustomLayout object
Set pptLayout = PPT.ActivePresentation.Slides(1).CustomLayout
'Run the OpenFile function to get an Open File dialog box. It returns a String containing the file and path.
strFilePath = OpenFile()
'Open the Excel file
Set objWorkbook = Excel.Application.Workbooks.Open(strFilePath)
'Grab the first Worksheet in the Workbook
Set objWorksheet = objWorkbook.Worksheets(1)
'Loop through each used row in Column A
For i = 2 To objWorksheet.Range("A65536").End(xlUp).Row
Set PPT = GetObject(, "PowerPoint.Application")
Set pptNewSlide = PPT.ActivePresentation.Slides.AddSlide(PPT.ActivePresentation.Slides.Count + 1, pptLayout)
PPT.ActivePresentation.Slides(1).Shapes("picture 9").Copy
pptNewSlide.Shapes.Paste
'Get the number of columns in use on the current row
Dim LastCol As Long
Dim boldWords As String
'Find the words to bold
boldWords = "Release Date: ,Distributor: ,Director: ,Genre: ,Starring: "
LastCol = objWorksheet.Rows(i).End(xlToRight).Column
If LastCol = 16384 Then LastCol = 1 'For some reason if only column 1 has data it returns 16384, so correct it
'Build a string of all the columns on the row
str = ""
str = "Release Date: " & str & objWorksheet.Cells(i, 4).Value & Chr(13) & _
"Distributor: " & objWorksheet.Cells(i, 18).Value & Chr(13) & _
"Director: " & objWorksheet.Cells(i, 7).Value & Chr(13) & _
"Genre: " & objWorksheet.Cells(i, 16).Value & Chr(13) & _
"Starring: " & objWorksheet.Cells(i, 10).Value & Chr(13) & Chr(13) & _
objWorksheet.Cells(i, 6).Value
sfile = Cells(i, 13) & ".jpg"
Set PPT = GetObject(, "PowerPoint.Application")
'Write the string to the slide
pptNewSlide.Shapes(2).TextFrame.TextRange.Text = objWorksheet.Cells(i, 2).Value 'This enters the film Title
PPT.ActivePresentation.Slides(PPT.ActivePresentation.Slides.Count).Shapes(1).TextFrame.TextRange.Text = str
BoldSomeWords PPT.ActivePresentation.Slides(PPT.ActivePresentation.Slides.Count).Shapes(1), str, boldWords
'~~> Get hold of PPT instance
Set PPT = GetObject(, "Powerpoint.Application")
'~~> Reference the slide which contains picture placeholders
Set pptSlide = PPT.ActivePresentation.Slides(PPT.ActivePresentation.Slides.Count)
Imagenum = 1
For Each oPPtShp In pptSlide.Shapes.Placeholders
' Run the Error handler "ErrHandler" when an error occurs.
Const SpecialCharacters As String = "!,#,#,$,%,^,&,*,(,),{,[,],},:,."
Dim originalstring As String
Dim convertedstring As String
On Error Resume Next
'~~> Only need to work on Picture place holders
If oPPtShp.PlaceholderFormat.Type = ppPlaceholderPicture Then
With oPPtShp
oPPtShpName = oPPtShp.Name
pptSlide.Shapes(oPPtShpName).Select
If oPPtShp.Name = oPPtShpName And Imagenum = 1 Then paths = "C:\"
If oPPtShp.Name = oPPtShpName And Imagenum = 2 Then paths = "C:\"
If oPPtShp.Name = oPPtShpName And Imagenum = 3 Then paths = "C:\"
If oPPtShp.Name = oPPtShpName And Imagenum = 1 Or oPPtShp.Name = oPPtShpName And Imagenum = 2 Then originalstring = objWorkbook.Worksheets(1).Cells(i, 2).Value
convertedstring = "Test" 'originalstring
For Each char In Split(SpecialCharacters, ",")
convertedstring = Replace(convertedstring, char, " ")
Next
If oPPtShp.Name = oPPtShpName And Imagenum = 1 Then pptSlide.Shapes.AddPicture paths & convertedstring & ".jpg", msoFalse, msoTrue, _
.Left, .Top, .Width, .Height Else
If oPPtShp.Name = oPPtShpName And Imagenum = 2 Then pptSlide.Shapes.AddPicture paths & convertedstring & " - Copy" & ".jpg", msoFalse, msoTrue, _
.Left, .Top, .Width, .Height Else
If oPPtShp.Name = oPPtShpName And Imagenum = 3 Then pptSlide.Shapes.AddPicture paths & convertedstring & " - Copy (2)" & ".png", msoFalse, msoTrue, _
.Left, .Top, .Width, .Height
' If oPPtShp.Name = oPPtShpName And Imagenum = 3 Then pptSlide.Shapes.AddPicture paths & objWorkbook.Worksheets(1).Cells(i, 11).Value & " - Copy (2)" & ".png", msoFalse, msoTrue, _
.Left, .Top, .Width, .Height
DoEvents
End With
Imagenum = Imagenum + 1
End If
Next
On Error Resume Next
'Assign the Trailer to the Powerpoint View Trailer Image
Set oSh = pptSlide.Shapes("WatchTrailer")
With oSh.ActionSettings(ppMouseClick)
.Hyperlink.Address = objWorksheet.Cells(i, 8).Value
End With
Set oPPtSlide = Nothing
Set oPPt = Nothing
Next
End Sub
Function OpenFile()
'Dim the File Dialog object and string
Dim objFileDialog As FileDialog
Dim strFile As String
'Set the objFileDialog to an instance of the FileDialog object
Set objFileDialog = Application.FileDialog(msoFileDialogFilePicker)
'Set the Properties of the objFileDialog object
objFileDialog.AllowMultiSelect = False
objFileDialog.ButtonName = "Select"
objFileDialog.InitialView = msoFileDialogViewDetails
objFileDialog.Title = "Select Excel File"
objFileDialog.InitialFileName = "C:\"
objFileDialog.Filters.Clear
objFileDialog.Filters.Add "Excel", "*.xls; *.xlsx", 1
objFileDialog.FilterIndex = 1
'Show the FileDialog box
objFileDialog.Show
'Set strFile to the first record of the SelectedItems property of our FileDialog
strFile = objFileDialog.SelectedItems(1)
'Return the File Path string
OpenFile = strFile
End Function
Sub BoldSomeWords(shp As Object, str As String, boldWords As String)
Dim word As Variant
Dim iStart As Integer, iEnd As Integer
'Convert the list of words in to an iterable array, and
' iterate it.
For Each word In Split(boldWords, ",")
'Loop just in case there are duplicates
Do Until InStr(iEnd + 1, str, word) = 0
iStart = InStr(iStart + 1, str, word)
iEnd = iStart + Len(word)
shp.TextFrame.TextRange.Characters(iStart, Len(word)).Characters.Font.Bold = msoTrue
Loop
Next
End Sub
Different versions of PPT behave differently wrt placeholders. If you add an image, some will automatically drop the image into the first available empty content or picture placeholder, some will just drop the image onto the slide.
I'd be more inclined to record the position/size of each placeholder then delete them. THEN drop in the images and position/size them to match.
If you MUST use the placeholders for some reason (and I'm sure there are lots of good reasons), you might want to distribute a dummy "not available" image with your code and drop that in when the needed image isn't available.
Or ... perhaps better yet ... if the image isn't available and it's a content placeholder, put in some dummy text, something unique. Now the PH isn't empty any longer so when you drop in the next image, it won't go into that PH. Finally, at the end, look for any PH type shapes and if they contain your unique text, delete the text (leaving you with an empty PH again).
Something that might be worth a go (though as Steve says versions behave differently)
Add the picture to a temp blank slide and cut
Select the correct placehoder on the real slide
ActiveWindow.View.Paste