我正试图从Excel(VBA)创建一个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
您的情况中的问题源于您使用的绑定类型-后期绑定。在这种情况下,某些VBA常量不会被识别,而是被视为变量。
首先-如果您将VBE编辑器设置为require variable declaration
模式,那么您会更早地认识到这个问题,因为我在代码中可以找到的所有三个vba常量都会标记为变量:
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"
第三个-为什么它适用于两个常数中的第一个?因为两者都被识别为值等于0的变量。在这两种情况下,0都是幻灯片类型的可接受参数。但0不是TextBox类型的可接受值。。