2015-10-15 80 views
0

我試圖通過excel將模板應用於powerpoint。 PowerPoint模板通過插入 - >對象嵌入到我的Excel文件中。我已成功使用.applytemplate方法從文件應用模板,但我無法調整代碼以引用嵌入的PowerPoint模板。我嘗試使用OLEObject,但我擔心這是不正確的。請查看下面的代碼。將模板應用於Excel VBA中的powerpoint從嵌入式模板文件

Sub ppCreate() 

Dim myPP As PowerPoint.Application 
Dim myPres As PowerPoint.Presentation 
Dim activeSlide As PowerPoint.Slide 
Dim ppObj As OLEObject 

' Create instance of PowerPoint 
Set myPP = CreateObject("Powerpoint.Application") 

' For automation to work, PowerPoint must be visible 
myPP.Visible = True 


' Create a presentation 
Set myPres = myPP.Presentations.Add 

' Set slide view to Slide Only 
myPP.ActiveWindow.ViewType = ppViewSlide 

'Resize to 4:3 
myPres.PageSetup.SlideSize = 2 

'Add a slide 
Set activeSlide = myPres.Slides.Add(1, ppLayoutBlank) 

'Import Template 

Worksheets("CBRDATA").Select 
Set ppObj = ActiveSheet.OLEObjects("ppObj")  'NOT WORKING 
myPres.ApplyTemplate (ppObj)      'NOT WORKING 
myPres.ApplyTemplate "C:\CBR_TEMPLATE_COVER.potx" 'WORKING 
Worksheets("CBR").Select 

End Sub 

更新:

'Test if template exists in C:\ 
If Dir("C:\CBR_TEMPLATE_COVER.potx") = "" Then 
    'Open/Save the embedded template to C:\ 
    Set tempPP = CreateObject("Powerpoint.Application") 
    Worksheets("CBRDATA").OLEObjects("ppObj").Verb 0 
    tempPP.Visible = True 
    Set tempPres = tempPP.ActivePresentation 
    tempPres.SaveCopyAs ("C:\CBR_TEMPLATE_COVER.potx") 
    tempPres.Close 
Else: 
End If 

' Create instance of PowerPoint 
Set myPP = CreateObject("Powerpoint.Application") 

回答

1

這不起作用,因爲ActiveSheet.OLEObjects("ppObj")是類型OLEObject,不PowerPoint.Presentation

Set ppObj = ActiveSheet.OLEObjects("ppObj")  'NOT WORKING 

當對象開放的POTX文件上手動雙擊(實際上它打開使用POTX爲模板,一個新的空白PPTX),你的賦值語句上面沒有做任何的是,它試圖而是要將OLEObject放置在預期的演示文稿中,並且始終會失敗。

那麼,如何「打開」OLEObject呢? OLEObject有一個.Verb方法,下面將執行對象的默認動作,在嵌入包對象的情況下,通常是「打開」它們。

解決方案

'Import Template 
'## This should Open the template 
Worksheets("CBRDATA").OLEObjects("ppObj").Verb 0   

'## Assign the ActivePresentation to your ppObj variable 
Set ppObj = myPP.ActivePresentation 

編者按:嵌入式OLEObjects是衆所周知的問題,並且可能不是故事的東西的理想場所像文檔模板 :)

+0

大衛你好,謝謝你的回答。根據你的最終評論,我在想也許我應該先將嵌入式文檔保存到文件中,然後從文件中應用模板。 – Citanaf

+0

我的最終評論只是一個建議,如果**您使用OLEObject作爲「共享」和維護文檔模板的方式,那可能不是最佳做法。我不會建議嘗試使用VBA來完成你所提到的。如果您想從磁盤上打開POTX,那麼您應該分發POTX,並從*已知或高度期待的位置*(如C:\ Users \%USERNAME%\ AppData \ Roaming \ Microsoft \ Templates \文檔主題「,或允許用戶使用」FileDialog「選擇它。 –

+0

該文檔是更大的儀表板的一部分,可根據用戶選擇創建標準化的Powerpoint。我更改了我的代碼以測試C:\中是否存在模板,如果找不到它,它會創建一個新的PowerPoint並將其保存到該文件夾​​。在這種情況下,我的代碼的其餘部分不需要聯繫。上面提供的細節。再次感謝你的幫助 – Citanaf