VBA Excel --> PWP - Blank when copy - vba

I have a little issue with my macro. I know it's not the perfect one but at least it works.
The only thing is that when I go step by step it is going perfectly but when I run it all the new slides are blank.
Do you have an idea how to improve that ?
Sub paste_toPPT()
Dim PowerPointApp As Object
Dim pptApp As Object
Dim pptPres As Object
Dim myRange As Excel.Range
Dim path As String
Dim DestinationPPT As String
Dim saveName As String
Dim image As Object
Dim IDe As String
Dim count As Integer
'Create an Instance of PowerPoint
On Error Resume Next
'Is PowerPoint already opened?
Set pptApp = GetObject(Class:="PowerPoint.Application")
'Clear the error between errors
Err.Clear
'If PowerPoint is not already open then open PowerPoint
If pptApp Is Nothing Then Set pptApp = CreateObject(Class:="PowerPoint.Application")
'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
'Open template
DestinationPPT = "C:\Users\user\Desktop\ID Card\Kpi ID.pptx"
Set pptPres = pptApp.Presentations.Open(DestinationPPT)
Windows("KPI List - P2P KPI.xlsm").Activate
count = WorksheetFunction.CountA(Sheets("KPI List").Range("E:E")) - 1
For i = 8 To count
Worksheets("KPI List").Select
'ThisWorkbook.Sheets("KPI List").Select
IDe = Worksheets("KPI List").Range(Cells(i, 5), Cells(i, 5))
ThisWorkbook.Sheets("ID").Range("F4:F4") = IDe
'Set the range to copy
Windows("KPI List - P2P KPI.xlsm").Activate
Worksheets("ID").Select
Worksheets("ID").Shapes.Range(Array("Group 57")).Select
Selection.Copy
'Add slide & Paste data
pptPres.Windows(1).Activate
Set mySlide = pptPres.Slides.Add(1, 12)
mySlide.Select
pptApp.CommandBars.ExecuteMso ("PasteSourceFormatting")
Next i
pptPres.SaveAs DestinationPPT
End Sub

Try the code below, explanations inside the code as comments:
Sub paste_toPPT()
Dim pptApp As Object
Dim pptPres As Object
Dim myRange As Excel.Range
Dim path As String
Dim DestinationPPT As String
Dim saveName As String
Dim image As Object
Dim IDe As String
Dim count As Integer
' added 2 worksheet objects
Dim wsKPI As Worksheet
Dim wsID As Worksheet
'Create an Instance of PowerPoint
On Error Resume Next
'Is PowerPoint already opened?
Set pptApp = GetObject(, "PowerPoint.Application")
'Clear the error between errors
Err.Clear
'If PowerPoint is not already open then open PowerPoint
If pptApp Is Nothing Then Set pptApp = CreateObject("PowerPoint.Application")
'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
'Open template
DestinationPPT = "C:\Users\user\Desktop\ID Card\Kpi ID.pptx"
Set pptPres = pptApp.Presentations.Open(DestinationPPT)
' no need to Activate the workbook first, just set the worksheet objects
Set wsKPI = Workbooks("KPI List - P2P KPI.xlsm").Sheets("KPI List")
Set wsID = Workbooks("KPI List - P2P KPI.xlsm").Sheets("ID")
count = WorksheetFunction.CountA(ws.Range("E:E")) - 1
For i = 8 To count
IDe = wsKPI.Range(wsKPI.Cells(i, 5), wsKPI.Cells(i, 5))
wsID.Range("F4:F4") = IDe
' first add the slide , later do the copy>>paste as close as can be
Set mySlide = pptPres.Slides.Add(1, 12)
' Set the range to copy (no need to Select first)
wsID.Shapes.Range(Array("Group 57")).Copy
mySlide.Select
pptApp.CommandBars.ExecuteMso ("PasteSourceFormatting")
Next i
pptPres.Save
End Sub

Related

Error: "Method 'rows' of object '_Global' failed

For some reason even though I am referring to the oSheet variable it is returning the error as if I am referring to a global variable?
PS I am trying to populate a combobox in word with a contractor names from an excel sheet I have created. I searched in google and here, none of the solutions have worked for me unfortunately. I believe the error lies within the For Each statement.
Sub Macro3()
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
Dim ExcelWasNotRunning As Boolean
Dim WorkbookToWorkOn As String
'specify the workbook to work on
WorkbookToWorkOn = "C:\Users\Nathan\Desktop\KTC\VBA Experiment\Excel Files\testExcel.xlsx"
'If Excel is running, get a handle on it; otherwise start a new instance of Excel
On Error Resume Next
Set oXL = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set oXL = New Excel.Application
End If
On Error GoTo Err_Handler
'If you want Excel to be visible, you could add the line: oXL.Visible = True here; but your code will run faster if you don't make it visible
'Open the workbook
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn)
'Process each of the spreadsheets in the workbook
For Each oSheet In oXL.ActiveWorkbook.Worksheets
'put guts of your code here
'get next sheet
If oSheet.Cells(Rows.Count, 1).End(xlUp).Row = 1 Then
lastRow = 2
Else
lastRow = oSheet.Cells(Rows.Count, 1).End(xlUp).Row
End If
' For i = 2 To lastRow
' workZonerForm.contracterCMB.AddItem oSheet.Cells(i, 1)
' Next i
MsgBox lastRow
Next oSheet
If ExcelWasNotRunning Then
oXL.Quit
End If
'Make sure you release object references.
Set oRng = Nothing
Set oSheet = Nothing
Set oWB = Nothing
Set oXL = Nothing
'quit
Exit Sub
Err_Handler:
MsgBox WorkbookToWorkOn & " caused a problem. " & Err.Description, vbCritical, _
"Error: " & Err.Number
If ExcelWasNotRunning Then
oXL.Quit
End If
End Sub

Get the FileName and Path of the PowerPoint Presentation that the Excel is Attached as Object

Goal: To get the Path and FileName of the PowerPoint Presentation in which my current Excel VBA is attached in as Object.
The screen-shot below might explain better what I mean:
This is the code I used to have to find the needed Presentation in case there are a few Presentations open at the same time (but I'm not able so far to get the Presentation in which I'm located in - and I don't want to pass the Presntation Name) :
Option Explicit
Sub UpdatePowerPoint(PowerPointFile)
Dim ppProgram As Object
Dim ppPres As Object
Dim CurOpenPresentation As Object
On Error Resume Next
Set ppProgram = GetObject(, "PowerPoint.Application")
On Error GoTo 0
If ppProgram Is Nothing Then
Set ppProgram = CreateObject("PowerPoint.Application")
Else
If ppProgram.Presentations.Count > 0 Then
For Each CurOpenPresentation In ppProgram.Presentations ' loop through all open presnetations (check Full Name: Path and name)
Dim CleanFullName As String * 1024
CleanFullName = Replace(CurOpenPresentation.FullName, "%20", " ") ' replace Sharepoint characters %20 with Space ("_")
If StrComp(PowerPointFile, CleanFullName, vbTextCompare) = 0 Then
Set ppPres = CurOpenPresentation
Exit For
End If
Next CurOpenPresentation
End If
End If
End Sub
Question: Am I missing an Excel/Office "Trick", which "ties" the Excel File somehow with the Presentation it's located in ? Maybe some other solution ?
Something along these lines
Sub T()
Dim ppProgram As PowerPoint.Application
Dim ppPresentation As PowerPoint.Presentation
Dim ppSlide As PowerPoint.Slide
Dim ppShape As PowerPoint.Shape
Dim objExcel As Excel.Application
Set ppProgram = GetObject(, "PowerPoint.Application")
For Each ppPresentation In ppProgram.Presentations
For Each ppSlide In ppPresentation.Slides
For Each ppShape In ppSlide.Shapes
If ppShape.Type = msoEmbeddedOLEObject Then
Set objExcel = ppShape.OLEFormat.Object.Application
if objExcel.ActiveWorkbook.Name=activeworkbook.name then stop
Else
End If
Next ppShape
Next ppSlide
Next ppPresentation
End Sub

Reopening recently closed instances of Excel

If I use the below code to close all instances of Excel that are currently open what would I need to use to reopen all the instances of Excel that were just closed? I know I'll have to change the below to save a filepath somewhere but just not sure what the actual code should be.
Public Sub CloseAllExcel()
On Error GoTo handler
Dim xl As Excel.Application
Dim wb As Excel.Workbook
Do While xl Is Nothing
Set xl = GetObject(, "Excel.Application")
For Each wb In xl.Workbooks
wb.Save
wb.Close
Next
xl.Quit
Set xl = Nothing
Loop
Exit Sub
handler:
If Err <> 429 Then 'ActiveX component can't create object
MsgBox Err.Description, vbInformation
End If
End Sub
This stores file paths of the workbooks to a text file. If you run this macro with False as the input, this will open all of the recently closed files. (Not tested)
Public Sub CloseAllExcel(Closing As Boolean)
On Error GoTo handler
Dim xl As Excel.Application
Dim wb As Excel.Workbook
Dim strPath As String
strPath = "C:\path.txt"
If Close Then
Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
Do While xl Is Nothing
Set xl = GetObject(, "Excel.Application")
For Each wb In xl.Workbooks
oFile.WriteLine Application.ActiveWorkbook.FullName
wb.Save
wb.Close
Next
oFile.Close
Set fso = Nothing
Set oFile = Nothing
xl.Quit
Set xl = Nothing
Loop
Exit Sub
Else
Dim FileNum As Integer
Dim DataLine As String
FileNum = FreeFile()
Open strPath For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine
Workbooks.Open DataLine
Wend
Exit Sub
End If
handler:
If Err <> 429 Then 'ActiveX component can't create object
MsgBox Err.Description, vbInformation
End If
End Sub
You could use a Very-Hidden worksheet, where you'll keep all of the Files currently open.
Note: If you want there is an option to Save and Read for the Registry.
Sub CloseAllExcel Code:
Option Explicit
Public Sub CloseAllExcel()
On Error GoTo handler
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim i As Long
Dim Hidws As Worksheet
On Error Resume Next
Set Hidws = ThisWorkbook.Worksheets("Admin")
On Error GoTo 0
If Hidws Is Nothing Then ' check if there isn't "Admin" sheet exists in the workbook
Set Hidws = ThisWorkbook.Sheets.Add(Before:=ThisWorkbook.Worksheets(Worksheets.Count))
Hidws.Name = "Admin"
Hidws.Visible = xlSheetVeryHidden ' make the "Admin" sheet very-hidden
End If
i = 1
Do While xlApp Is Nothing
Set xlApp = GetObject(, "Excel.Application")
For Each wb In xlApp.Workbooks
Hidws.Range("A" & i).Value = wb.FullName ' save each workbook full name and path in column "A" in "Admin" very-hidden sheet
i = i + 1
wb.Close True
Next
xlApp.Quit
Set xlApp = Nothing
Loop
Exit Sub
handler:
If Err <> 429 Then 'ActiveX component can't create object
MsgBox Err.Description, vbInformation
End If
End Sub
Sub RestoreExcelLastSession Code: reads the files (names and Path) from Column "A" in "Admin" very-hidden sheet.
Sub RestoreExcelLastSession()
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim i As Long
Dim Hidws As Worksheet
On Error Resume Next
Set Hidws = ThisWorkbook.Worksheets("Admin")
On Error GoTo 0
If Hidws Is Nothing Then ' check if "Admin" sheet exists
MsgBox "No Files have been restored"
Exit Sub
End If
i = 1
Do While Hidws.Range("A" & i).Value <> "" ' loop through cells in Column "A"
Set xlApp = CreateObject("Excel.Application") ' open a new Excel instance per file
xlApp.Workbooks.Open (Hidws.Range("A" & i).Value)
i = i + 1
Set xlApp = Nothing
Loop
End Sub

How to paste excel data into powerpoint and still allow the user to edit data

I was wondering if there was a way of exporting/pasting an excel range into powerpoint, while still allowing the user to edit the result. The code I keep seeing on the internet pastes data from excel into powerpoint as a picture. Below is an example:
Sub export_to_ppt(ByVal sheetname As String, ByVal initialSelection As String) ', ByVal cols As Integer, ByVal rows As Integer)
Application.ScreenUpdating = False
Dim rng As Range
Dim PowerPointApp As Object
Dim myPresentation As Object
Dim mySlide As Object
Dim myShape As Object
'Copy Range from Excel
'Set rng = ThisWorkbook.ActiveSheet.Range("B17:D50")
'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")
'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
'Optimize Code
Application.ScreenUpdating = False
'Create a New Presentation
Set myPresentation = PowerPointApp.Presentations.Add
'Add a slide to the Presentation
Set mySlide = myPresentation.Slides.Add(1, 12) '12 = ppLayoutBlank
'Copy Excel Range
Dim rowCount As Integer
Dim colcount As Integer
Dim i As Integer
Dim No_sheets As Integer
No_sheets = Worksheets("Control_Sheet").Range("AP2").Value + 2
For i = 3 To No_sheets
Worksheets("Control_Sheet").Activate
Worksheets("Control_Sheet").Cells(i, 42).Select
If Worksheets("Control_Sheet").Cells(i, 42).Value = sheetname Then
rowCount = Worksheets("Control_Sheet").Cells(i, 44).Value
colcount = Worksheets("Control_Sheet").Cells(i, 43).Value
GoTo resume_copy
End If
Next i
resume_copy:
Worksheets(sheetname).Activate
Worksheets(sheetname).Range(initialSelection).Select
Selection.Resize(rowCount, colcount).Select
Selection.Copy
'Paste to PowerPoint and position
Application.Wait Now + TimeValue("00:00:01")
mySlide.Shapes.PasteSpecial DataType:=2 '2 = ppPasteEnhancedMetafile
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
'Set position:
myShape.Left = 1
myShape.Top = 1
myShape.Width = 950
PowerPointApp.Visible = True
PowerPointApp.Activate
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
Replace:
mySlide.Shapes.PasteSpecial DataType:=2
With:
mySlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject, DisplayAsIcon:=msoFalse, link:=msoFalse
Hope this helps,
TheSilkCode
You can, but this process was very buggy for me when running a large ppt deck. This works by using the ppt shapes position as the location of the paste. Use a template ppt slide to test, you can paste tables and graphs this way.
Dim myApp As PowerPoint.Application
Dim myPres As PowerPoint.Presentation
Dim myStatsSlide As PowerPoint.Slide
Set myApp = New PowerPoint.Application
Set myPres = myApp.ActivePresentation
Set myStatsSlide = myPres.Slides(1)
Dim mySheet As Worksheet
Set mySheet = ActiveSheet
'Copy table as table, not image
Dim mySumTable As Range
Set mySumTable = mySheet.Range("A1:C5")
mySumTable.Copy
myStatsSlide.Shapes.Placeholders(1).Select
myPres.Windows(1).View.Paste
'Copy Chart, as chart not image
Dim monoChart As ChartObject
'MONO CHART
monoChart.Select
ActiveChart.ChartArea.Copy
Debug.Print monoChart.Name
myStatsSlide.Shapes.Placeholders(2).Select
myPres.Windows(1).View.Paste
Debug.Print monoChart.Name

How can I Make PowerPoint slides for excel each Range in VBA

How can I make powerpoint slides based on Excel Range A2:B2. All the characters(countryname) for excel rows A1 to A10 make it as a Powerpoint Slide.
Here is the Code that is throwing an array error:
Sub PasteMultipleSlides()
Dim myPresentation As Object
Dim mySlide As Object
Dim PowerPointApp As Object
Dim shp As Object
Dim MySlideArray As Variant
Dim MyRangeArray As Variant
Dim x As Long
On Error Resume Next
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
Err.Clear
'If PowerPoint is not already open then Exit
If PowerPointApp Is Nothing Then
MsgBox "PowerPoint Presentation is not open, aborting."
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
'Make PowerPoint Visible and Active
PowerPointApp.ActiveWindow.Panes(2).Activate
'Create a New Presentation
Set myPresentation = PowerPointApp.ActivePresentation
'List of PPT Slides to Paste to
MySlideArray = Array(2, 3, 4, 5, 6)
'List of Excel Ranges to Copy from
MyRangeArray = Array(Sheet1.Range("A2:B10"))
'Loop through Array data
For x = LBound(MySlideArray) To UBound(MySlideArray)
'Copy Excel Range
MyRangeArray(x).Copy
'Paste to PowerPoint and position
On Error Resume Next
Set shp = myPresentation.Slides(MySlideArray(x)).Shapes.PasteSpecial(DataType:=2) 'Excel 2007-2010
Set shp = PowerPointApp.ActiveWindow.Selection.ShapeRange 'Excel 2013
On Error GoTo 0
'Center Object
With myPresentation.PageSetup
shp.Left = (.SlideWidth \ 2) - (shp.Width \ 2)
shp.Top = (.SlideHeight \ 2) - (shp.Height \ 2)
End With
Next x
'Transfer Complete
Application.CutCopyMode = False
ThisWorkbook.Activate
MsgBox "Complete!"
End Sub