PowerPointにはオリジナルのレイアウト(ユーザー設定レイアウト)を作成する機能が用意されています(下記サイト参照)。
オブジェクトとしてもCustomLayoutsコレクション、CustomLayoutオブジェクトが用意されているので、ユーザー設定レイアウトをマクロから取り扱うことができます。
今回は、指定したスライドにユーザー設定レイアウトを適用する簡単なマクロを紹介します。
名前指定できないユーザー設定レイアウト
ユーザー設定レイアウトを指定するのは簡単で、SlideオブジェクトのCustomLayoutプロパティを変更するだけです。
ActivePresentation.Slides(1).CustomLayout = (CustomLayoutオブジェクト)
ただし、CustomLayoutオブジェクトの取得には少々クセがあります。
CustomLayoutオブジェクトは、CustomLayoutsコレクションのItemメソッド(既定メンバーなので省略可能)によって取得できるのですが、引数がVariant型になっていて、説明文に“コレクションから取得する 1 つのオブジェクトの名前またはインデックス番号を指定します”とあるにも関わらず、実際には、ユーザー設定レイアウト名で取得しようとすると、下記のように実行時エラーが発生し、インデックス番号でしか取得できないようになっています。
Public Sub Test()
Dim myCustomLayout As PowerPoint.CustomLayout
Set myCustomLayout = ActivePresentation.SlideMaster.CustomLayouts.Item("白紙") '実行時エラー
'Set myCustomLayout = ActivePresentation.SlideMaster.CustomLayouts.Item("Blank") '実行時エラー
'Set myCustomLayout = ActivePresentation.SlideMaster.CustomLayouts.Item(8) '問題なし
Stop
End Sub
実行時エラー ‘-2147024809 (80070057)’:
CustomLayouts (不明なメンバー) : 引数の種類が正しくありません。コレクション インデックス (文字列または整数)が必要です。
指定したスライドにユーザー設定レイアウトを適用する
そこで、一手間掛かってしまうのですが、ユーザー設定レイアウト名からインデックスを取得する自作関数を間に挟むことで、CustomLayoutオブジェクトを取得するようにします。
Public Sub Sample()
'指定したスライドにユーザー設定レイアウトを適用する
'※下記コードでは「和風レイアウト」という名前のユーザー設定レイアウトを適用
Dim mySlideMaster As PowerPoint.Master
Dim myCustomLayout As PowerPoint.CustomLayout
Dim idx As Long
Set mySlideMaster = ActivePresentation.SlideMaster
idx = GetCustomLayoutsIndex(mySlideMaster, "和風レイアウト")
If idx <> 0 Then
Set myCustomLayout = mySlideMaster.CustomLayouts(idx)
ActivePresentation.Slides(1).CustomLayout = myCustomLayout
End If
End Sub
Private Function GetCustomLayoutsIndex(ByVal TargetSlideMaster As PowerPoint.Master, _
ByVal CustomLayoutName As String) As Long
'ユーザー設定レイアウト名からインデックスを取得する
Dim cl As PowerPoint.CustomLayout
Dim ret As Long
ret = 0 '初期化
For Each cl In TargetSlideMaster.CustomLayouts
If cl.Name = CustomLayoutName Then
ret = cl.Index
Exit For
End If
Next
GetCustomLayoutsIndex = ret
End Function
以上のようなコードで、マクロから指定したスライドにユーザー設定レイアウトを適用できるわけですが、「白紙」のように標準で用意されているレイアウトを適用する場合には、下記のようにSlideオブジェクトのLayoutプロパティを指定(PpSlideLayout列挙)した方が簡潔になります。
Public Sub Sample2() ActivePresentation.Slides(1).Layout = ppLayoutBlank End Sub























この記事へのコメントはありません。