You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历样式修改NextParagraphStyle时遇运行时错误91(Word VBA)

解决VBA宏运行时错误91:对象变量未正确赋值

问题描述

运行用于批量修改Word快速段落样式后续样式的宏时,触发运行时错误91,报错停在语句Let thisStyle = .Styles(iCount)。该宏的用途是将50余种快速样式集中的多数段落样式后续样式设置为Body Text,减少Normal样式的使用。

原错误代码

Sub StyleFollowingBodyText()
    ' Charles Kenyon 15 December 2024
    ' Set the following style for most QuickStyle paragraph styles to be Body Text
    Dim StyleCount As Long
    Dim thisStyle As Style
    Dim iCount As Long
    '
    With ActiveDocument
        Let StyleCount = .Styles.Count
        For iCount = 1 To StyleCount
            Let thisStyle = .Styles(iCount)
            If thisStyle.QuickStyle = True Then
                If thisStyle.Type = wdStyleTypeParagraph Or wdStyleTypeLinked Then
                    If thisStyle.NameLocal <> "Normal" Then
                        thisStyle.NextParagraphStyle = "Body Text"
                    End If
                End If
            End If
        Next iCount
    End With
End Sub

错误原因及修正方案

  • 核心错误:thisStyle是对象类型变量,VBA中给对象变量赋值必须使用Set语句,原代码用Let直接赋值导致对象引用错误。
  • 额外逻辑修正:原代码中If thisStyle.Type = wdStyleTypeParagraph Or wdStyleTypeLinked Then存在逻辑漏洞,wdStyleTypeLinked未关联到thisStyle.Type,会被当作布尔值处理,需补充完整条件判断。

修改后的完整代码

Sub StyleFollowingBodyText()
    ' Charles Kenyon 15 December 2024
    ' Set the following style for most QuickStyle paragraph styles to be Body Text
    Dim StyleCount As Long
    Dim thisStyle As Style
    Dim iCount As Long
    '
    With ActiveDocument
        Let StyleCount = .Styles.Count
        For iCount = 1 To StyleCount
            Set thisStyle = .Styles(iCount) ' 修正:使用Set赋值对象变量
            If thisStyle.QuickStyle = True Then
                ' 修正:完整判断样式类型
                If thisStyle.Type = wdStyleTypeParagraph Or thisStyle.Type = wdStyleTypeLinked Then
                    If thisStyle.NameLocal <> "Normal" Then
                        thisStyle.NextParagraphStyle = "Body Text"
                    End If
                End If
            End If
        Next iCount
    End With
End Sub

内容的提问来源于stack exchange,提问作者Charles Kenyon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 11:35:59