Add a custom slide layout in PowerPoint using Excel VBA? - vba

I have created a PowerPoint with custom slide layouts. I want to be able to create a new slide using one of these custom layouts using Excel VBA, but I cannot figure out the correct syntax.
This is the code I currently have:
Sub runPPT()
Application.ScreenUpdating = False
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Sheets("SG2")
Dim pptName As String
Dim ppt As Object
Dim myPres As Object
Dim slds As Object
Dim sld As Object
MsgBox ("Please choose PowerPoint to open.")
pptName = openDialog()
Set ppt = CreateObject("PowerPoint.Application")
Set myPres = ppt.Presentations.Open(pptName)
Set slds = myPres.Slides
'This is where I want to add my custom layout
'My layouts all have similar names like "Gate 2 Main" if that helps
Set sld = slds.AddSlides(Slides.Count + 1, ActivePresentation.SlideMaster.CustomLayouts(1))
Application.ScreenUpdating = True
End Sub
Private Function openDialog()
Dim fd As Office.FileDialog
Dim txtFileName As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
openDialog = txtFileName
End Function

I was able to fix my issue by changing my code to the following:
Sub runPPT()
Application.ScreenUpdating = False
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Sheets("SG2")
Dim pptName As String
Dim ppt As PowerPoint.Application
Dim myPres As PowerPoint.Presentation
Dim slds As PowerPoint.Slides
Dim sld As PowerPoint.slide
Dim oLayout As CustomLayout
MsgBox ("Please choose PowerPoint to open.")
pptName = openDialog()
Set ppt = CreateObject("PowerPoint.Application")
Set myPres = ppt.Presentations.Open(pptName)
Set slds = myPres.Slides
Set sld = slds.Add(myPres.Slides.Count + 1, ppLayoutBlank)
For Each oLayout In myPres.Designs("Gate Main").SlideMaster.CustomLayouts
If oLayout.Name = "Gate 2 Main" Then
sld.CustomLayout = oLayout
Exit For
End If
Next
Application.ScreenUpdating = True
End Sub
Private Function openDialog()
Dim fd As Office.FileDialog
Dim txtFileName As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
openDialog = txtFileName
End Function

Related

How to replace text in Footers while toggling Footer.Visible?

I have VBA code which replaces the value of the footer.text with "" and turns off footer visibility by Footer.Visible = msoFalse
Every time I set Footer.Visible to msoFalse, the footer text that was changed to "" reverts to the original text. (This can be seen while using PowerPoint -> insert -> Header & Footer -> Slide tab -> Footer dialogue box.)
The entry before changing the footer.text to "" returns.
If I do not change the visibility with Footer.visible=msoFalse, the change to the "" value is accepted.
'This will select the file/folder
Function select_folder()
Dim Filepicker As FileDialog
Dim mypath As String
Set Filepicker = Application.FileDialog(msoFileDialogFolderPicker)
With Filepicker
.Title = "Select folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
.ButtonName = "Select(&S)"
If .Show = -1 Then
mypath = .SelectedItems(1) & "\"
Else
End
End If
End With
'Workbooks.Open fileName:=mypath
NextCode:
select_folder = mypath
Set Filepicker = Nothing
End Function
Sub ppt_delete()
Dim strInFold As String, strFile As String, PrsSrc As PowerPoint.Presentation
Dim extension As String
Dim PPApp As PowerPoint.Application
Dim PPSlide As PowerPoint.Slide
strInFold = select_folder
extension = "*.ppt*"
strFile = Dir(strInFold & extension)
Do While strFile <> ""
' Reference instance of PowerPoint
On Error Resume Next
' Check whether PowerPoint is running
Set PPApp = GetObject(, "PowerPoint.Application")
If PPApp Is Nothing Then
' PowerPoint is not running, create new instance
Set PPApp = CreateObject("PowerPoint.Application")
' For automation to work, PowerPoint must be visible
PPApp.Visible = True
End If
On Error GoTo 0
DoEvents
Set PrsSrc = PPApp.Presentations.Open(Filename:=strInFold & strFile)
For Each PPSlide In PrsSrc.Slides
PPSlide.HeadersFooters.Footer.Visible = msoTrue
PPSlide.HeadersFooters.Footer.Text = ""
'PPSlide.HeadersFooters.Footer.Visible = msoFalse
'you can comment and uncomment above line to test
DoEvents
Next PPSlide
PPApp.ActivePresentation.Save
PPApp.ActivePresentation.Close
strFile = Dir
Loop
PPApp.Quit
End Sub
Additional info. The script will first choose a folder where the .ppt* files are located. Script will check all the .ppt extensions in the folder, and make the changes.
How can I do this:
PPSlide.HeadersFooters.Footer.Visible = msoTrue
PPSlide.HeadersFooters.Footer.Text = ""
PPSlide.HeadersFooters.Footer.Visible = msoFalse
and make the changes to "" visible in powerpoint -> insert-> Header & Footer -> Slide tab -> Footer dialogue box.
Apparently, the footer value is hidden in the presentation. this is the reason why it always comes back.
The solution was to assign the footer.text to "" save and close, reopen the ppt, then switch to PPSlide.HeadersFooters.Footer.Visible = msoFalse
Another approach: Tag the parent slide with the text you want to apply, then when you want to make the hidden footer visible again, set it to the saved text in the tag. Advantage is that this is near instant, where saving and reopening could take quite a while if the presentation is large.
Sub Test()
Dim osl As Slide
For Each osl In ActivePresentation.Slides
With osl.HeadersFooters.Footer
.Text = "New Text"
SetText osl, "TEXT", .Text
.Visible = False
.Visible = True
.Text = GetText(osl, "TEXT")
End With
Next
End Sub
Function GetText(osl, sTagname As String)
GetText = osl.Tags(sTagname)
End Function
Function SetText(osl As Slide, sTagname As String, sText As String)
osl.Tags.Add sTagname, sText
End Function

Method 'ThisWorkbook' of object '_Global' failed - Exporting comments from Word to Excel

I am trying to export comments and corresponding text from Word to Excel using this code. I copied and pasted the code into VBA as such:
Option Explicit
Public Sub FindWordComments()
'Requires reference to Microsoft Word v14.0 Object Library
Dim myWord As Word.Application
Dim myDoc As Word.Document
Dim thisComment As Word.Comment
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Dim destSheet As Worksheet
Dim rowToUse As Integer
Dim colToUse As Long
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
Set destSheet = ThisWorkbook.Sheets("Sheet1")
colToUse = 1
With fDialog
.AllowMultiSelect = True
.Title = "Import Files"
.Filters.Clear
.Filters.Add "Word Documents", "*.docx"
.Filters.Add "Word Macro Documents", "*.docm"
.Filters.Add "All Files", "*.*"
End With
If fDialog.Show Then
For Each varFile In fDialog.SelectedItems
rowToUse = 2
Set myWord = New Word.Application
Set myDoc = myWord.Documents.Open(varFile)
For Each thisComment In myDoc.Comments
With thisComment
destSheet.Cells(rowToUse, colToUse).Value = .Range.Text
destSheet.Cells(rowToUse, colToUse + 1).Value = .Scope.Text
destSheet.Columns(2).AutoFit
End With
rowToUse = rowToUse + 1
Next thisComment
destSheet.Cells(1, colToUse).Value = Left(myDoc.Name, 4)
'Put name of interview object in cell A1
destSheet.Cells(1, colToUse + 1).Value = ActiveDocument.Words.Count
'Put the number of words in cell B1
Set myDoc = Nothing
myWord.Quit
colToUse = colToUse + 2
Next varFile
End If
End Sub
Public Sub PrintFirstColumnOnActiveSheetToSheetName()
ActiveSheet.Name = ActiveSheet.Range("A1")
End Sub
and VBA returns with the error from the title of my post, and highlighting the code:
Set destSheet = ThisWorkbook.Sheets("Sheet1")
Not sure where to go from here, might I add I am an extremely novice coder/VBA user. I just learned now how to create a macro.
Because you are running code from within Word, you first need to initialize an instance of Excel and then reference to the workbook of choice
So insert the following code in the head of your sub and replace "WorkbookName" with the name of your Workbook. Then replace ThisWorkbook in your code with wb
Dim objExcelApp As Object
Dim wb As Object
Set objExcelApp = CreateObject("Excel.Application")
Set wb = objExcelApp.Workbooks("WorkbookName")
If the Workbook is closed replace last line with
Set wb = objExcelApp.Workbooks.Open("C:/Folder1/Book1.xlsm")

Worksheets(1) Ignore hidden worksheet

I've been working my way through a macro that will merge the first visible worksheet from an entire folder of selected workbooks. With plenty of help, I have the code working for the first worksheet in each workbook, but it is picking up hidden worksheets and I only want the first visible sheet. Here is the code so far:
Option Explicit
Function GetFolder(strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Sub CombineFiles()
Dim Path As String
Dim FileName As String
Dim Wkb As Workbook
Dim WS As Worksheet
Application.EnableEvents = False
Application.ScreenUpdating = False
Path = GetFolder("Navigate to folder")
FileName = Dir(Path & "\*.xl??", vbNormal)
Do Until FileName = ""
Set Wkb = Workbooks.Open(FileName:=Path & "\" & FileName, ReadOnly:=True, UpdateLinks:=False)
Wkb.Worksheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Wkb.Close False
FileName = Dir()
Loop
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
you can loop until a visible worksheet is found
Dim i As Long
i = 1
Do While Wkb.Worksheets(i).Visible = False
If i >= Wkb.Worksheets.Count Then
MsgBox "No visible sheet found"
Exit Do
End If
i = i + 1
Loop
Debug.Print Worksheets(i).Name 'first visible sheet

Getting Subscription out of range Error

Code is running well while checking if "Test_Worksheet" worksheet exists in workbook file opened by dialog. Workbook File is opening correctly & if "Test_Worksheet" sheet exists in that file then debug.print (in Sub ChkSalfile) give "Name is True".
But if sheet not available in Workbook, then "Subscription out of Range" error coming. Please help. My code is as below
Sub Main()
Dim salefor As Workbook
Dim salpathfileName As String, salfileName As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
.InitialFileName = "*SAL*.*"
result4 = .Show
If (result4 <> 0) Then
salfileName = Dir(.SelectedItems(1))
salpathfileName = .SelectedItems(1)
Else
'if user pressed CANCEL - exit sub
Application.ScreenUpdating = True
MsgBox "User pressed CANCEL"
Exit Sub
End If
End With
Set salefor = Workbooks.Open(salfileName, ReadOnly:=True)
Call ChkSalfile(salfileName, salefor)
End Sub
Sub ChkSalfile (salfileName As String, salefor As Workbook)
Dim chksalsheet As String
chksalsheet = DoesWorkSheetExist("Test_Worksheet", salfileName)
If chksalsheet = True Then
Debug.Print "Name is " & chksalsheet
Else
Debug.Print "File not found"
End If
End Sub
Option Explicit
Public Function DoesWorkSheetExist(WorkSheetName As String, Optional WorkBookName As String)
Dim WS As Worksheet
On Error Resume Next
If WorkBookName = vbNullString Then
Set WS = Sheets(WorkSheetName)
Else
Set WS = Workbooks(WorkBookName).Sheets(WorkSheetName)
End If
On Error GoTo 0
DoesWorkSheetExist = Not WS Is Nothing
End Function
It seems that your settings in the VBA project editor are set to break on any errors. Change this setting to break only on unhandled errors:
Tools --> Options --> General Tab --> Error Trapping --> check "Break on Unhadled Errors"
That said, don't Dim your variable as a String when it is a Boolean:
Dim chksalsheet As Boolean ' <-- Not as String

ActiveX can't create object powerpont vba

I am trying to copy 1st slide from the powerpoint and insert it at the end but I am getting ActiveX can't create object on the line
ActivePresentation.Slides(1).Copy
This is my full code and I've added the reference to microsoft powerpoint library as well
Option Explicit
Dim myFile, Fileselected As String, Path As String, objPPT As Object
Dim activeSlide As PowerPoint.Slide
Sub Generate_PPTs()
Application.ScreenUpdating = False
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose Template PPT File."
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
Fileselected = .SelectedItems(1)
End With
Path = Fileselected
Set objPPT = CreateObject("PowerPoint.Application")
Set objPPT = objPPT.Presentations.Open(Path)
Debug.Print objPPT.Name
ActivePresentation.Slides(1).Copy
ActivePresentation.Slides.Paste Index:=objPPT.Slides.Count + 1
Set activeSlide = objPPT.Slides(objPPT.Slides.Count)
Application.ScreenUpdating = True
Set objPPT = Nothing
End Sub
Try edited code below, I have ppApp As PowerPoint.Application and Dim ppPres As PowerPoint.Presentation :
Option Explicit
Dim myFile, Fileselected As String, Path As String, objPPT As Object
Dim ppApp As PowerPoint.Application
Dim ppPres As PowerPoint.Presentation
Dim activeSlide As PowerPoint.Slide
Sub Generate_PPTs()
Application.ScreenUpdating = False
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose Template PPT File."
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
Fileselected = .SelectedItems(1)
End With
Path = Fileselected
Dim i As Integer
Set ppApp = New PowerPoint.Application
i = 1
ppApp.Presentations.Open Filename:=Path ' 'PowerPointFile = "C:\Test.pptx"
Set ppPres = ppApp.Presentations.Item(i)
' for debug
Debug.Print ppPres.Name
ppPres.Slides(1).Copy
ppPres.Slides.Paste Index:=ppPres.Slides.Count + 1
Set activeSlide = ppPres.Slides(ppPres.Slides.Count)
Application.ScreenUpdating = True
Set ppPres = Nothing
Set ppApp = Nothing
End Sub