首页 > 解决方案 > 查找文档中是否存在数组中的任何样式

问题描述

我有这段代码来测试文档中是否存在样式。

Sub StyleExists()
MsgBox Style("Test")
End Sub

Function Style(strStyle) As Boolean
   Dim t
   On Error Resume Next
   Style = True
   Set t = ActiveDocument.Styles(strStyle)
   If Err.Number <> 0 Then Style = False
   Err.Clear
End Function

而不是检查一种风格,我想对多种风格进行检查。我的想法是将样式列表存储在一个数组中并检查它们是否存在。

如何扩展代码?

标签: vbams-word

解决方案


数组是一个糟糕的解决方案。VBA 提供了一个更有用的对象,即脚本字典,可从 Microsoft Scripting 运行时库中获得。以下代码显示了如何填充合适的脚本字典,然后如何检查样式名称是否在禁止名称列表中。

Option Explicit

Public ForbiddenStyleName                       As Scripting.Dictionary


Public Sub PopulateForbiddenStyleNameDict()

    Set ForbiddenStyleName = New Scripting.Dictionary
    ' use one .add per stylename
    With ForbiddenStyleName

        ' Scripting dictionaries require an Key and a value for each .Add
        ' In this case we just duplicate the key as a value.
        .Add Key:=ActiveDocument.Styles(wdStyleNormal).NameLocal, Item:=ActiveDocument.Styles(wdStyleNormal).NameLocal
        .Add ActiveDocument.Styles(wdStyleHeading1).NameLocal, ActiveDocument.Styles(wdStyleNormal).NameLocal
        .Add "UserStyle2", "UserStyle2"
        .Add "UserStyle4", "UserStyle4"
        ' ...etc
    End With

End Sub


Public Sub DemonstrationOfForbiddenStyleExists()

    PopulateForbiddenStyleNameDict

    ' Pass the style name as a string
    If ForbiddenStyleName.Exists("UserStyle2") Then

        MsgBox "UserStyle2 is used in the document"

    End If

End Sub

推荐阅读