vba - 查找文档中是否存在数组中的任何样式
问题描述
我有这段代码来测试文档中是否存在样式。
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
而不是检查一种风格,我想对多种风格进行检查。我的想法是将样式列表存储在一个数组中并检查它们是否存在。
如何扩展代码?
解决方案
数组是一个糟糕的解决方案。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
推荐阅读
- c# - 如何检查列的值是否为假我想插入我的数据
- delphi - Delphi Tokyo Debug:“已在您的系统中找到一个调试器 [...]”错误
- function - 返回两个列表中最短者的 Scheme 函数
- ruby - Rubymine 不重新分配共享上下文变量
- jquery - 如何在(ALL)单选按钮中获取两个单选按钮值,注意 All 是我的代码中的单选按钮
- vba - VBA AutoFill 相邻动态列导致错误?
- javascript - swagger 对象作为使用 Joi 的有效负载验证
- powershell-workflow - 禁用 UAC,重新启动并安装程序
- html - 防止 Angular 中的 div 溢出
- c# - 在 C# 中设置 AntiForgeryToken 以重定向到 HttpGet 方法