Move (Cut&Paste) Powerpoint Slides with Sections information by VBA - vba

I am looking for a solution to select some slides and cut or copy and paste at another location while keeping the section information.
I have seen PPT does not support it out of the box (see http://answers.microsoft.com/en-us/office/forum/office_2013_release-powerpoint/copying-sections-to-a-new-powerpoint/2c723b0d-d465-4ab6-b127-6fdfc195478c?db=5)
and also some VBA Script examples here Exporting PowerPoint sections into separate files
PPTalchemy provides some Add-In but unfortunately the code is not available. See here http://www.pptalchemy.co.uk/powerpoint_hints_and_tips_tutorials.html#2010
Moreover it does not suit to move sections easily within the same presentation.
Any idea how to do this?
Many thanks.
Thierry

To move a section within a presentation, including all slides within the section, call this procedure with the index of the section to be moved and it's new location:
Option Explicit
' ********************************************************************************
' VBA Macro for PowerPoint, written by Jamie Garroch of http://YOUpresent.co.uk/
' ********************************************************************************
' Purpose : Moves a specified section of slides to a new section location
' Inputs : lSectionIndex - the index of the section to be moved
' lNewPosition - the index of the position to move to
' Outputs : None.
' ********************************************************************************
Public Sub MoveSection(lSectionIndex As Long, lNewPosition As Long)
On Error GoTo errorhandler
With ActivePresentation
.SectionProperties.Move lSectionIndex, lNewPosition
End With
Exit Sub
errorhandler:
Debug.Print "Couldn't move section due to the following error: " & Err & ", " & Err.Description
End Sub

This is finally the code I use to move multiple sections selected by slides:
Sub MoveSelectedSections()
' Slides are copied ready to be pasted
Dim lngNewPosition As Long
'Debug.Print ""
'Debug.Print "###Move Sections..."
lngNewPosition = InputBox("Enter a destination section index:")
lngNewPosition = CInt(lngNewPosition) ' Convert String to Int
Call MoveSectionsSelectedBySlides(ActivePresentation, lngNewPosition)
End Sub
Function MoveSectionsSelectedBySlides(oPres As Presentation, lNewPosition As Long)
On Error GoTo errorhandler
' Activate input presentation
oPres.Windows(1).Activate
' Get Selected Sections Indexes
' http://www.thespreadsheetguru.com/the-code-vault/2014/4/3/copy-selected-slides-into-new-powerpoint-presentation
Dim i, cnt As Integer
Dim SelectedSlides As SlideRange
Dim SectionIndexes() As Long
If ActiveWindow.Selection.Type <> ppSelectionSlides Then
MsgBox "No slides selected"
Exit Function
End If
Set SelectedSlides = ActiveWindow.Selection.SlideRange
' selection order is reverse see http://www.pptfaq.com/FAQ00869_Create_a_custom_show_from_current_slide_selection_using_VBA.htm
'Fill an array with sectionIndex numbers
ReDim SectionIndexes(1 To SelectedSlides.Count)
cnt = 0
For i = 1 To SelectedSlides.Count
' Check if already present in array
If Not Contains(SectionIndexes, SelectedSlides(i).sectionIndex) Then
cnt = cnt + 1
SectionIndexes(cnt) = SelectedSlides(i).sectionIndex
End If
Next i
ReDim Preserve SectionIndexes(1 To cnt)
' Move Sections to lNewPosition, first last
For i = 1 To cnt
With oPres
.SectionProperties.Move SectionIndexes(i), lNewPosition
End With
Debug.Print "Section #" & SectionIndexes(i) & " moved to " & lNewPosition
Next i
Exit Function
errorhandler:
Debug.Print "Couldn't move section due to the following error: " & Err & ", " & Err.Description
End Function
Function Contains(arr, v) As Boolean
' http://stackoverflow.com/a/18769246/2043349
Dim rv As Boolean, i As Long ' Default value of boolean is False
For i = LBound(arr) To UBound(arr)
If arr(i) = v Then
rv = True
Exit For
End If
Next i
Contains = rv
End Function

Related

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

Group shapes in same height across multiple rows in Powerpoint using VBA

I want to create a VBA macro in PPT to Group shapes in same height across multiple rows in Powerpoint using VBA. My initial step would be ideally like this image:
Group Textboxes row wise
There is a matrix of textboxes in many rows and columns evenly distributed vertically & horizontally. I want to select all the shapes altogether and run a macro to group the textboxes row wise, into multiple rows. Code below is copied and not final yet, Appreciate any help, snippets for this, thanks a lot.
Sub GroupSameHeightObjects()
' Dimension the variables.
Dim shapeObject As shape
Dim lSlideNumber As Long
Dim strPrompt, strTitle As String
Dim ShapeList() As String
Dim count As Long
' Initialize the counter.
count = 0
' Make sure PowerPoint is in slide view.
If ActiveWindow.ViewType <> ppViewSlide Then
' Set up the error message.
strPrompt = "You must be in slide view to run this macro." _
& " Change to slide view and run the macro again."
strTitle = "Not In Slide View"
' Display the error message.
MsgBox strPrompt, vbExclamation, strTitle
' Stop the macro.
End
End If
' Get the current slide number.
lSlideNumber = ActiveWindow.Selection.SlideRange.SlideNumber
' Loop through the shapes on the slide.
For Each shapeObject In _
ActivePresentation.Slides(lSlideNumber).Shapes
' See whether shape is a placeholder.
If shapeObject.Type <> msoPlaceholder Then
' Increment count if the shape is not a placeholder.
count = count + 1
' Get the name of the shape and store it in the ShapeList
' array.
ReDim Preserve ShapeList(1 To count)
ShapeList(count) = shapeObject.Name
End If
Next shapeObject
' If more than 1 object (excluding a placeholder object) is found,
' group the objects.
If count > 1 Then
With ActivePresentation.Slides(lSlideNumber).Shapes
' Group the shapes together.
.Range(ShapeList()).Group.Select
End With
Else
Select Case count
' One shape found.
Case 1
' Set up the message.
strPrompt = "Only one shape found." _
& " You need at least two shapes to group."
strTitle = "One Shape Available"
' Zero shapes found.
Case 0
' Set up the message.
strPrompt = "No shapes found. You need to have at " _
& "least two shapes, excluding placeholders."
strTitle = "No Shapes Available"
' An error occurred.
Case Else
' Set up the message.
strPrompt = "The macro found an error it could not correct."
strTitle = "Error"
End Select
' Display the message.
MsgBox strPrompt, vbExclamation, strTitle
End If
End Sub
I don't have time right now to write/test any code, but if I had to do this, I'd start with something like this snippet I had from another project:
Sub GroupCertainShapes()
Dim x As Long
Dim sTemp As String
Dim aShapeList() As String
Dim lShapeCount As Long
With ActivePresentation.Slides(1)
' iterate through all shapes on the slide
' to get a count of shapes that meet our condition
For x = 1 To .Shapes.Count
' Does the shape meet our condition? count it.
If .Shapes(x).Type = msoAutoShape Then
lShapeCount = lShapeCount + 1
End If
Next
' now we know how many elements to include in our array,
' so redim it:
ReDim aShapeList(1 To lShapeCount)
' Reset the shape counter
lShapeCount = 0
' Now add the shapes that meet our condition
' to the array:
For x = 1 To .Shapes.Count
' apply some criterion for including the shape or not
If .Shapes(x).Type = msoAutoShape Then
lShapeCount = lShapeCount + 1
aShapeList(lShapeCount) = .Shapes(x).Name
End If
Next
' and finally form a group from the shapes in the array:
If UBound(aShapeList) > 0 Then
.Shapes.Range(aShapeList).Group
End If
End With
End Sub
A couple of things that may not give you fully what you're after but that'll save you some trouble down the line:
Sub GroupSameHeightObjects()
' Dimension the variables.
Dim shapeObject As shape
Dim lSlideNumber As Long
' This will dim strPrompt as a variant
' Dim strPrompt, strTitle As String
Dim strPrompt as string, strTitle as string
Dim ShapeList() As String
Dim count As Long
' Initialize the counter.
count = 0
' Make sure PowerPoint is in slide view.
If ActiveWindow.ViewType <> ppViewSlide Then
' Set up the error message.
strPrompt = "You must be in slide view to run this macro." _
& " Change to slide view and run the macro again."
strTitle = "Not In Slide View"
' Display the error message.
MsgBox strPrompt, vbExclamation, strTitle
' Stop the macro.
' See previous comment
'End
Exit Sub
End If
' Get the current slide number.
' Nope, you want the SlideIndex; SlideNumber gives you the number that'll
' appear when you use PPT's slide numbering features; if the user sets the
' starting number to something other than 1, your code will break
'lSlideNumber = ActiveWindow.Selection.SlideRange.SlideNumber
lSlideNumber = ActiveWindow.Selection.SlideRange.SlideIndex
' Loop through the shapes on the slide.
For Each shapeObject In _
ActivePresentation.Slides(lSlideNumber).Shapes
' See whether shape is a placeholder.
If shapeObject.Type <> msoPlaceholder Then
' Increment count if the shape is not a placeholder.
count = count + 1
' Get the name of the shape and store it in the ShapeList
' array.
' I've learned not to trust shape names in PPT
' I'd dim ShapeList as an array of shapes and then
' Set ShapeList(count) = shapeObject
ReDim Preserve ShapeList(1 To count)
ShapeList(count) = shapeObject.Name
End If
Next shapeObject
' You could include this next bit in the following Case selector,
' Case > 1 ... etc.
' If more than 1 object (excluding a placeholder object) is found,
' group the objects.
If count > 1 Then
With ActivePresentation.Slides(lSlideNumber).Shapes
' Group the shapes together.
.Range(ShapeList()).Group.Select
End With
Else
Select Case count
' One shape found.
Case 1
' Set up the message.
strPrompt = "Only one shape found." _
& " You need at least two shapes to group."
strTitle = "One Shape Available"
' Zero shapes found.
Case 0
' Set up the message.
strPrompt = "No shapes found. You need to have at " _
& "least two shapes, excluding placeholders."
strTitle = "No Shapes Available"
' An error occurred.
Case Else
' Set up the message.
strPrompt = "The macro found an error it could not correct."
strTitle = "Error"
End Select
' Display the message.
MsgBox strPrompt, vbExclamation, strTitle
End If
End Sub

VBA Array error

I have the following code which uses two for loops (Prod and Dev)
There are many values in the array but i have taken only two for the example
What it does is, it copies the value from one excel to the other.
Now, there is a probability that file NSA_103_B_Roles.xls doesnot exist
In that case, i dont want the code to take any action, so i have put on error resume next
But still it is printing the value in the excel which doesnot exist,
What is the reason?
Private Sub CommandButton1_Click()
Prod = Array("ZS7_656", "PCO_656")
Dev = Array("NSA_103", "DCA_656")
For lngCounter1 = LBound(Dev) To UBound(Dev)
For lngCounter = LBound(Prod) To UBound(Prod)
On Error Resume Next
Set Zz2 = Workbooks.Open("C:\Users\*****\Desktop\New folder\" &
Dev(lngCounter1) & "_B_Roles.xls")
Zz2.Sheets(Dev(lngCounter1) & "_B_Roles").Range("A1").Value = "anirudh"
ThisWorkbook.Sheets(Prod(lngCounter)).Range("A2").Value =
Zz2.Sheets(Dev(lngCounter1) & "_B_Roles").Range("A1").Value
On Error GoTo 0
Next lngCounter
Next lngCounter1
End Sub
Try the code below, explanation inside the code's comments :
Private Sub CommandButton1_Click()
Dim Zz2 As Workbook
Prod = Array("ZS7_656", "PCO_656")
Dev = Array("NSA_103", "DCA_656")
For lngCounter1 = LBound(Dev) To UBound(Dev)
For lngCounter = LBound(Prod) To UBound(Prod)
' ==== this section starts the error handling ===
On Error Resume Next
Set Zz2 = Workbooks.Open("C:\Users\*****\Desktop\New folder\" & _
Dev(lngCounter1) & "_B_Roles.xls")
On Error GoTo 0
If Zz2 Is Nothing Then ' <-- unable to find the file
MsgBox "unable to find the specified file", vbCritical
Exit Sub
End If
' === Up to Here ===
Zz2.Sheets(Dev(lngCounter1) & "_B_Roles").Range("A1").Value = "anirudh"
ThisWorkbook.Sheets(Prod(lngCounter)).Range("A2").Value = Zz2.Sheets(Dev(lngCounter1) & "_B_Roles").Range("A1").Value
Next lngCounter
Next lngCounter1
End Sub

VBA how to copy images / inline shapes from Word to powerpoint

I am trying to write a macro to find and copy all the graphs/images inline in a word document and paste them into individual slides in a new powerpoint. However when I run into multiple runtime errors. Here's the entire code.
Sub wordtoppt()
'This macro copies all pictures out of a word document of your choice and into a new powerpoint presentation.
'Two reference libraries need to be open - Word and Powerpoint. Go Tools > References, and tick the relevant box.
Dim wdApp As Word.Application 'Set up word and powerpoint objects
Dim wdDoc As Word.Document
Dim pptApp As PowerPoint.Application
Dim pptShw As PowerPoint.Presentation
Dim pptChart As PowerPoint.Shape
Dim pptSld As PowerPoint.Slide
On Error GoTo 0
Dim wcount As Integer 'Number of open word documents
Dim doclist() As String 'Collects the names of open word documents
Dim desc As String 'inputbox text
Dim chosendoc As Integer 'stores the index number of your selected word document
Dim ccount As Integer 'number of shapes in the word document
Dim wellpasted As Integer 'Counts the number of shapes that have successfully been pasted into powerpoint.
Application.ScreenUpdating = False
'Establishes link with word.
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
On Error GoTo 0
If wdApp Is Nothing Then 'Error message if Word is not open
MsgBox "Error: Word is not open." & Chr(10) & Chr(10) & "Is word actually open? This is a bug."
Exit Sub
End If
'Counts the number of word documents open
wcount = CInt(wdApp.Documents.Count)
ReDim doclist(wcount) 'resizes string array of word documents
If wcount = 0 Then 'Error message if Word is open, but there are no documents open
MsgBox "There are no word documents open!" & Chr(10) & "Open a word document and try again"
Exit Sub
End If
'text for input box
desc = "Which document would you like to extract the graphs from?" & Chr(10) & Chr(10) & "Type the number in the box (one number only)." & Chr(10) & Chr(10)
'input boxes for selection of word document
If wcount = 1 Then 'if only one document open
myinput = MsgBox("Do you want to paste graphs from " & wdApp.Documents(1).Name & "?", vbYesNo, "From Release Note to Powerpoint")
If myinput = vbYes Then
chosendoc = 1
Else
Exit Sub
End If
Else
For i = 1 To wcount 'multiple documents open
doclist(i) = wdApp.Documents(i).Name
desc = desc & i & ": " & doclist(i) & Chr(10)
Next
myinput = InputBox(desc, "From Release Note to Powerpoint")
If IsNumeric(myinput) And myinput <= wcount Then 'Error handling - if cancel is clicked, or anything other than a number is typed into the input box.
chosendoc = CInt(myinput)
Else
If myinput = "" Then 'clicking cancel, or leaving input box blank
MsgBox "You didn't enter anything!"
Exit Sub
Else 'if you type a short novel
MsgBox "You didn't enter a valid number!" & Chr(10) & "(Your response was " & myinput & ")"
Exit Sub
End If
End If
End If
'Error handling, for chart-free word documents.
If wdApp.Documents(chosendoc).InlineShapes.Count = 0 Then
MsgBox "There are no charts in this Word Document!"
Exit Sub
End If
'Opens a new powerpoint presentation
Set pptApp = CreateObject("PowerPoint.Application")
Set pptShw = pptApp.Presentations.Add
'PowerPoint.Application
'Sets up slide dimensions
Dim sldwidth As Integer
Dim sldheight As Integer
sldwidth = pptShw.PageSetup.SlideWidth
sldheight = pptShw.PageSetup.SlideHeight
wellpasted = 0
Dim shapecount As Integer 'Number of shapes in the word document
shapecount = wdApp.Documents(chosendoc).InlineShapes.Count
For j = 1 To shapecount 'Adds in the correct number of slides into the powerpoint presentation
Set pptSld = pptShw.Slides.Add(pptShw.Slides.Count + 1, ppLayoutBlank)
Next
For j = 1 To shapecount 'loops through all shapes in the document
On Error GoTo Skiptheloop 'sometimes some objects don't paste. This is a way to skip over them.
'Application.Wait Now + (1 / 86400)
wdApp.Documents(chosendoc).InlineShapes(j).Range.Copy 'copies chart
Set pptSld = pptShw.Slides(j)
pptSld.Shapes.Paste 'pastes chart
'Application.CutCopyMode = False
With pptSld.Shapes(1) 'resizes and aligns shapes
.LockAspectRatio = msoTrue 'Currently sets charts to the height of the slide. Alternatively can scale to 100%
.Height = sldheight
.Left = (sldwidth / 2) - (.Width / 2)
.Top = (sldheight / 2) - (.Height / 2)
End With
wellpasted = wellpasted + 1 'if the chart was pasted successfully, increment by 1.
Skiptheloop:
Next
On Error GoTo 0
If (shapecount - wellpasted) <> 0 Then 'produces a message box if some shapes did not paste successfully.
MsgBox CStr(shapecount - wellpasted) & " (of " & CStr(shapecount) & ") shapes were not pasted. Best that you check all the graphs are in."
End If
Application.ScreenUpdating = True
pptApp.Activate 'brings powerpoint to the front of the screen
Exit Sub
End Sub
On the line pptSld.shapes.paste I get the error clipboard empty or cannot paste.
Any ideas?
I am using Simple solution for my job devided in two pars
1) Extract all images from word file
This can be done in two ways.
a. save as html which will create the folder filenam_files which will hold all the images in .png formate. There may be duplicate images in diff formate but .png will be unique.
b. change filename of word from file.docx to file.docx.zip
You can get the images at file.docx\word\media
There will be no duplicate images in this method.
2) Import all images in powerpoint.
1)
As you have already opened the document manually you can do one more step manually or record macro which will look like this.
Sub exportimages()
ChangeFileOpenDirectory "D:\temp\"
ActiveDocument.SaveAs2 FileName:="data.html", FileFormat:=wdFormatHTML, _
LockComments:=False, passWord:="", AddToRecentFiles:=True, WritePassword _
:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False, CompatibilityMode:=0
End Sub
2)
Close the word document.
Open Power point and paste this
Sub ImportABunch()
Dim strTemp As String
Dim strPath As String
Dim strFileSpec As String
Dim oSld As Slide
Dim oPic As Shape
strPath = "D:\temp\data_files\"
strFileSpec = "*.png" 'if you are using mehtod **a.** to extract the images.
'strFileSpec = "*.*" 'if you are using mehtod **b.** to extract the images.
strTemp = Dir(strPath & strFileSpec)
Do While strTemp <> ""
Set oSld = ActivePresentation.Slides.Add(ActivePresentation.Slides.Count + 1, ppLayoutBlank)
Set oPic = oSld.Shapes.AddPicture(FileName:=strPath & strTemp, _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, _
Left:=0, _
Top:=0, _
Width:=-1, _
Height:=-1)
strTemp = Dir
Loop
End Sub
You can write vbscript to combine this two steps together. I have no idea how to do that. You can google it.

Exporting PowerPoint sections into separate files

Every week I separate a long PowerPoint file into separate files. The files must be in PowerPoint format, and contain only the slides that are contained in the 'sections' from the PowerPoint file.
I need to:
1) Scan to see the number of slides in a given section
2) Make a file containing the slides within that section
3) Name that file the same as the name of the section, and save it in the same directory as the source file.
4) Repeat the process for subsequent sections.
5) Do this without damaging the original file.
I've located code (http://www.pptfaq.com/FAQ01086_Break_a_presentation_up_into_several_smaller_presentations.htm) that can break the file into many parts, but only by the number of files requested per file. I found some other helpful references here: http://skp.mvps.org/2010/ppt001.htm
I have coded in Basic and a number of easy gaming scripting languages. I need help understanding how this is done in VBA.
Since you do this very often, you should make an Add-In for this. The idea is to create copies of the presentation up to the number of sections in it, then open each one and delete the other sections and save.
Create blank presentation with macros enabled (*.pptm) and possibly add Custom UI button to call SplitIntoSectionFiles
Test and when satisfy, save as PowerPoint Add-In (*.ppam). Don't delete the pptm file!
Assuming that all are pptx files you are dealing with, you can use this code. It opens the splited pptx files in background, then remove irrelevant sections and save, close. If all goes well you get a message box.
Private Const PPT_EXT As String = ".pptx"
Sub SplitIntoSectionFiles()
On Error Resume Next
Dim aNewFiles() As Variant, sPath As String, i As Long
With ActivePresentation
sPath = .Path & "\"
For i = 1 To .SectionProperties.Count
ReDim Preserve aNewFiles(i)
' Store the Section Names
aNewFiles(i - 1) = .SectionProperties.Name(i)
' Force Save Copy as pptx format
.SaveCopyAs sPath & aNewFiles(i - 1), ppSaveAsOpenXMLPresentation
' Call Sub to Remove irrelevant sections
RemoveOtherSections sPath & aNewFiles(i - 1) & PPT_EXT
Next
If .SectionProperties.Count > 0 And Err.Number = 0 Then MsgBox "Successfully split " & .Name & " into " & UBound(aNewFiles) & " files."
End With
End Sub
Private Sub RemoveOtherSections(sPPT As String)
On Error Resume Next
Dim oPPT As Presentation, i As Long
Set oPPT = Presentations.Open(FileName:=sPPT, WithWindow:=msoFalse)
With oPPT
' Delete Sections from last to first
For i = .SectionProperties.Count To 1 Step -1
' Delete Sections that are not in the file name
If Not InStr(1, .Name, .SectionProperties.Name(i), vbTextCompare) = 1 Then
' Delete the Section, along with the slides associated with it
.SectionProperties.Delete i, True
End If
Next
.Save
.Close
End With
Set oPPT = Nothing
End Sub
Read about Custom UI if you don't have experience creating you own ribbon tab: msdn and use the "Office Custom UI Editor", I would use imageMso "CreateModule" for the button.
None of the proposed routines actually works, so I wrote mine from scratch:
Sub Split()
Dim original_pitch As Presentation
Set original_pitch = ActivePresentation
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
With original_pitch
.SaveCopyAs _
FileName:=fso.BuildPath(.Path, fso.GetBaseName(.Name) & ".pptx"), _
FileFormat:=ppSaveAsOpenXMLPresentation
End With
Dim i As Long
For i = 1 To original_pitch.SectionProperties.Count
Dim pitch_segment As Presentation
Set pitch_segment = Presentations.Open(Replace(original_pitch.FullName, "pptm", "pptx"))
section_name = pitch_segment.SectionProperties.Name(i)
For k = original_pitch.SectionProperties.Count To 1 Step -1
If pitch_segment.SectionProperties.Name(k) <> section_name Then pitch_segment.SectionProperties.Delete k, True
Next k
With pitch_segment
.SaveCopyAs _
FileName:=fso.BuildPath(.Path, original_pitch.SectionProperties.Name(i) & ".pptx"), _
FileFormat:=ppSaveAsOpenXMLPresentation
.Close
End With
Next i
MsgBox "Split completed successfully!"
End Sub
I could not get the above code to work.
However this is simpler and does work:
Sub SplitToSectionsByChen()
daname = ActivePresentation.Name
For i = 1 To ActivePresentation.SectionProperties.Count
For j = ActivePresentation.SectionProperties.Count To 1 Step -1
If i <> j Then ActivePresentation.SectionProperties.Delete j, True
Next j
ActivePresentation.SaveAs ActivePresentation.SectionProperties.Name(1)
ActivePresentation.Close
Presentations.Open (daname)
Next i
End Sub
I have edited fabios code a bit to look like this. And this works well for me in my PC
Option Explicit
Sub Split()
Dim original_File As Presentation
Dim File_Segment As Presentation
Dim File_name As String
Dim DupeName As String
Dim outputFname As String
Dim origName As String
Dim lIndex As Long
Dim K As Long
Dim pathSep As String
pathSep = ":"
#If Mac Then
pathSep = ":"
#Else
pathSep = "/"
#End If
Set original_File = ActivePresentation
DupeName = "TemporaryFile.pptx"
DupeName = original_File.Path & pathSep & DupeName
original_File.SaveCopyAs DupeName, ppSaveAsOpenXMLPresentation
origName = Left(original_File.Name, InStrRev(original_File.Name, ".") - 1)
For lIndex = 1 To original_File.SectionProperties.Count
If original_File.SectionProperties.SlidesCount(lIndex) > 0 Then
Set File_Segment = Presentations.Open(DupeName, msoTrue, , msoFalse)
File_name = File_Segment.SectionProperties.Name(lIndex)
For K = original_File.SectionProperties.Count To 1 Step -1
If File_Segment.SectionProperties.Name(K) <> File_name Then
Call File_Segment.SectionProperties.Delete(K, 1)
End If
Next K
outputFname = pathSep & origName & "_" & original_File.SectionProperties.Name(lIndex) & "_" & Format(Date, "YYYYMMDD")
With File_Segment
.SaveAs FileName:=.Path & outputFname & ".pptx", FileFormat:=ppSaveAsOpenXMLPresentation
.Close
End With
Set File_Segment = Nothing
End If
Next
Set original_File = Nothing
Kill DupeName
MsgBox "Split completed successfully!"
End Sub
This works for me (except for the filename):
Option Explicit
Sub ExportSlidesAsPresentations()
Dim oPres As Presentation
Dim sSlideOutputFolder As String
Set oPres = ActivePresentation
sSlideOutputFolder = oPres.Path & "\"
'Export all the slides in the presentation
Call oPres.PublishSlides(sSlideOutputFolder, True, True)
Set oPres = Nothing
End Sub