【问题标题】:Applying shading to character styles using Word VBA使用 Word VBA 对字符样式应用底纹
【发布时间】:2020-02-26 13:48:42
【问题描述】:

我创建了以下子例程(并使用了 VBA Express 中的函数)来为 Word 样式分配阴影和键盘快捷键。此代码适用于段落样式或链接样式,它适用于为字符样式分配键盘快捷键,但如果样式是字符样式(任何字符样式 - 我'在这里使用了“强调”)。

是否需要进行一些调整才能通过 VBA 将阴影应用于字符样式?提前致谢!

我尝试过多种风格,人物风格似乎是关键问题。

Sub Format_Style()
    Dim sStyle As String
    sStyle = "Emphasis"
    If StyleExists(sStyle) Then
       CustomizationContext = ActiveDocument
       KeyBindings.add wdKeyCategoryStyle, sStyle, BuildKeyCode(wdKeyControl, wdKeyAlt, wdKeyH)
       ActiveDocument.Styles(sStyle).Shading.BackgroundPatternColor = RGB(128, 128, 128)
       ActiveDocument.UpdateStyles
       Else
            MsgBox ("There is no style '" & sStyle & "' in this document.")
    End If
End Sub

Function StyleExists(StyleName As String) As Boolean
'from: http://www.vbaexpress.com/forum/showthread.php?15259-Solved-How-to-check-if-a-Word-Style-exists

    Dim MyStyle As Word.Style
    On Error Resume Next
    Set MyStyle = ActiveDocument.Styles(StyleName)
    ' Set MyStyle = ActiveDocument.AttachedTemplate.Styles(StyleName)
    StyleExists = Not MyStyle Is Nothing
End Function

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    阴影不是样式的属性。它是段落格式或字体的属性,具体取决于样式的类型。如果您不知道 sStyle 是什么类型的样式,您可以使用以下代码设置阴影。

      With ActiveDocument.Styles(sStyle)
        If .Type = wdStyleTypeCharacter Then
          .Font.Shading.BackgroundPatternColor = RGB(128, 128, 128)
        ElseIf .Type = wdStyleTypeParagraph Or .Type = wdStyleTypeLinked Then
          .ParagraphFormat.Shading.BackgroundPatternColor = RGB(128, 128, 128)
        End If
      End With
    

    编辑: 您还应该检查您对ActiveDocument.UpdateStyles 的使用情况,因为这可能不是您认为的那样。 UpdateStyles 方法从附加的模板复制样式并覆盖文档中具有相同名称的样式。 See the documentation here

    【讨论】:

    • @MichaelSchuler 如果这解决了您的问题,请接受作为帮助其他人解决相同问题的答案。
    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多