首页 > 解决方案 > 为什么我在访问形状对象时得到指定的值超出范围?

问题描述

我编写了这个函数来循环播放 vba 宏中的 powerpoint 幻灯片。我希望它循环遍历每张幻灯片上的形状并将文本设置为用户定义的默认值。

我得到了这个工作,现在由于某种原因在整理后它停止工作了。我得到 Run-time-error '-2147024809 (80070057) The specified value is out of range.

当我调试它时,它可以工作到某个幻灯片。在我的例子中,它是一张带有 5 个不同类型的带有文本的对象的测试幻灯片。有一个组。

尽管做了一些学习和培训,但这让我很难过。非常感谢一些帮助。我确定这是一个简单的解决方案,但我看不出我做错了什么。

Sub FontDefaultAllSlidesBody()
'Sets the text for all shapes on all slides in active presentation

'Set variables for functions
    Dim oSl As Slide
    Dim oSls As Slides
    Set oSls = ActivePresentation.Slides

'Set our default font settings
    For Each oSl In oSls
        For i = 1 To oSl.Shapes.Count
            With oSl.Shapes(i).TextFrame.TextRange.Font
                .Size = 16
                .Bold = msoFalse
                .Italic = msoFalse
                .Underline = msoFalse
                .Color = msoThemeColorAccent1
                .Name = "+mn-lt"
            End With
        Next i
     Next oSl
End Sub

标签: vbapowerpoint

解决方案


这可能足以解决问题。它测试每个形状以查看它是否可以包含文本,如果可以,它是否包含文本,然后才尝试修改文本。

我还稍微更改了循环以使用 Shape 对象;减少了很多打字并且(我认为)使您正在处理的内容更加清晰。

Sub FontDefaultAllSlidesBody()
'Sets the text for all shapes on all slides in active presentation

'Set variables for functions
    Dim oSl As Slide
    Dim oSls As Slides
' This will make it easier to read:
    Dim oSh as Shape
    Set oSls = ActivePresentation.Slides

'Set our default font settings
    For Each oSl In oSls
        For Each oSh in oSl.Shapes
          ' Add this to keep it from touching shapes that 
          ' can't contain text
          If oSh.HasTextFrame Then
            ' And skip shapes that have no text
            If oSh.TextFrame.HasText Then
              With oSh.TextFrame.TextRange.Font
                .Size = 16
                .Bold = msoFalse
                .Italic = msoFalse
                .Underline = msoFalse
                .Color = msoThemeColorAccent1
                .Name = "+mn-lt"
              End With
            End If ' HasText
          End If ' HasTextFrame
        Next  ' Shape
     Next oSl
End Sub

推荐阅读