从Excel中创buildPowerpoint并插入文本框失败

我试图从Excel(VBA)创build一个PowerPoint模板,并添加一个文本框到每个幻灯片。

代码行,我要添加文本框失败索引越界/没有活动的演示文稿。 这里有什么错误? 幻灯片的索引应该是好的 – 如果我手动设置索引没有改变。

Dim PowerPointApp As Object Set PowerPointApp = CreateObject("PowerPoint.Application") PowerPointApp.Visible = True Set objP = PowerPointApp.Presentations.Add objP.ApplyTemplate "" & Table1.Range("A1").Value & "draft.pptx" PowerPointApp.ActivePresentation.Slides.Add 1, ppLayoutTitle For i = 1 To 10 objP.ApplyTemplate "" & Table2.Range("A1").Value & "template.pptx" PowerPointApp.ActivePresentation.Slides.Add i + 1, ppLayoutBlank PowerPointApp.ActivePresentation.Slides(i + 1).Select Table3.ChartObjects(i).CopyPicture PowerPointApp.ActivePresentation.Slides(i + 1).Shapes.Paste PowerPointApp.ActivePresentation.Slides(i + 1).Shapes(1).Top = 150 PowerPointApp.ActivePresentation.Slides(i + 1).Shapes(1).Left = 50 PowerPointApp.ActivePresentation.Slides(i + 1).Shapes(1).Width = 400 PowerPointApp.ActivePresentation.Slides(i + 1).Shapes(1).Height = 300 'Exception occurs here PowerPointApp.ActivePresentation.Slides(i + 1).Shapes.AddTextbox(msoTextOrientationHorizontal, Left:=100, Top:=100, Width:=200, Height:=50).TextFrame.TextRange.Text = "Text" Next i 

您的情况中的问题源于您使用的绑定types – 后期绑定。 在这种情况下,一些VBA常量不被识别,并被视为variables。

首先 – 如果你设置你的VBE编辑器require variable declaration模式,那么你会更早地认识到这个问题,因为我可以在你的代码中find的所有三个vba常量将被标记为variables:

  ppLayoutTitle ppLayoutBlank msoTextOrientationHorizontal 

其次 – 为了避免这个问题,你需要把上面所有的常量转换成下面的数字:

  ppLayoutTitle =1 ppLayoutBlank =12 msoTextOrientationHorizontal =1 

通过这种方式:

 PowerPointApp.ActivePresentation.Slides.Add 1, 1 'ppLayoutTitle PowerPointApp.ActivePresentation.Slides.Add i + 1, 12 'ppLayoutBlank PowerPointApp.ActivePresentation.Slides(i + 1).Shapes.AddTextbox(1, Left:=100, Top:=100, Width:=200, Height:=50).TextFrame.TextRange.Text = "Text" 

第三 ,为什么它是为两个常量中的第一个工作? 因为两者都被认为是variables,其值等于0.在这两种情况下,0被认为是幻灯片types的参数。 但是0不被TextBoxtypes接受