简体   繁体   English

将样式应用于特定单词

[英]Applying style to particular words

I am using RegEx search, for find out the particular word in my MS-Word document, and the search result is stored into a variable. 我正在使用RegEx搜索,以查找我的MS-Word文档中的特定单词,并将搜索结果存储到变量中。 My problem is I want to apply a custom style only for the search result 我的问题是我只想对搜索结果应用自定义样式

Input: worldwide[1,2]. 输入:全球[1,2]。 Before, during or after the [1,3,4][1,2,4,5] [1,2,6,7,8] [1,2] [1,2] 在[1,3,4] [1,2,4,5] [1,2,6,7,8] [1,2] [1,2]之前,之中或之后

I am using the following code 我正在使用以下代码

Sub RegexReplaces()
    Set matches = New regExp
    Dim Sure As Integer
    Dim rng As Range
    matches.Pattern = "([\[\(][0-9, -]*[\)\]])"
    matches.Global = True
    Dim mat As MatchCollection
    Set mat = matches.Execute(ActiveDocument.Range)
    For Each m In mat
        Sure = MsgBox("Are you sure?" + m, vbOKCancel)
        If Sure = 1 Then
            m.Style = ActiveDocument.Styles("Heading 1")    'this is the error line
        Else
            MsgBox "not1111"
        End If
    Next m
End Sub

The For Each m In mat loop iterates over each item in the mat collection. For Each m In mat循环遍历垫集合中的每个项目。 M is not a range. M不是范围。 You need to set a range starting at m.FirstIndex and ending at m.FirstIndex + m.Length. 您需要设置一个范围,该范围以m.FirstIndex开始,以m.FirstIndex + m.Length结尾。 Then you'll need to select the range and use Selection.Style to style the range. 然后,您需要选择范围并使用Selection.Style设置范围的样式。

Sub RegexReplaces()
    Set matches = New regExp
    Dim Sure As Integer
    Dim rng As Range
    matches.Pattern = "([\[\(][0-9, -]*[\)\]])"
    matches.Global = True
    Dim mat As MatchCollection
    Set mat = matches.Execute(ActiveDocument.Range)
    For Each m In mat
        Sure = MsgBox("Are you sure?" + m, vbOKCancel)
        If Sure = 1 Then

            Set rng = ActiveDocument.Range(Start:=m.FirstIndex, End:=m.Length + m.FirstIndex)
            rng.Select
            Selection.Style = ActiveDocument.Styles("Heading 1")
        Else
            MsgBox "not1111"
        End If
    Next m
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM