【问题标题】:Find text only of style "Heading 1" (Range.Find to match style)仅查找样式“标题 1”的文本(Range.Find 以匹配样式)
【发布时间】:2012-02-15 01:59:05
【问题描述】:

我试图在我的文档中找到一些仅以“标题 1”样式出现的文本。到目前为止,没有任何用处。

示例代码:

With ThisDocument.Range.Find
    .Text = "The Heading"
    .Style = "Heading 1" 'Does not work
    .Execute
    If .Found Then Debug.Print "Found"
End With

只是一个注释,它一直停在目录中。

编辑:修复了拼写错误的“if”语句

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    您的代码对我来说看起来不错。我的最佳猜测是“标题 1”样式存在于您的目录中?

    下面的代码应该继续查找,找到所有匹配项:

    Dim blnFound As Boolean
    
    With ThisDocument.Range.Find
        .Text = "The Heading"
        .Style = "Heading 1"
    
        Do
            blnFound = .Execute
            If blnFound Then
                Debug.Print "Found"
            Else
                Exit Do
            End If
        Loop
    End With
    

    我希望这会有所帮助。

    【讨论】:

    • 谢谢伙计。有没有办法打印出每个找到的项目的信息(例如页码或尾随文本)?我需要在它之前插入一些文本,但似乎无法找出最好的方法/如果可能的话。
    • 用 Debug.Print .Parent.Information(wdFirstCharacterLineNumber) 替换 Debug.Print "Found" 将返回行号
    • 如果我希望脚本在不同语言版本的 Word 上运行会怎样?在匈牙利语中,它是 "Címsor 1" 而不是 "Heading 1" 等等。没有字符串键就没有内置引用吗?
    • @marczellm 我不相信您可以将默认样式引用为静态变量,至少就我的研究而言。这可能是因为您可以创建自己的样式或修改现有样式。我猜你只需要满足上述不同的语言,或者使用通配符?
    • @MattRowles 从那以后我似乎找到了内置样式引用问题的解决方案:msdn.microsoft.com/en-us/library/…,但我没有尝试。
    【解决方案2】:

    我在 Google 上找到了这个问题,但问题中的代码对我不起作用。我进行了以下更改来修复它:

    • 我将Selection.Find.Style = "Heading 1" 更改为一个对象。
    • 我更改了代码以从.Execute 而不是.Found 获取搜索的布尔结果

    我希望这对其他 Google 员工有所帮助。

    With ThisDocument.Range.Find
        .Text = "The Heading"
        .Style = ActiveDocument.Styles("Heading 1")
    
        Dim SearchSuccessful As Boolean
        SearchSuccessful = .Execute
    
        If SearchSuccessful Then
            ' code
        Else
            ' code
        End If
    End With
    

    【讨论】:

      【解决方案3】:

      我认为它不起作用的原因是因为您必须设置

      .format = true
      

      flag,您可能必须通过 .Styles 方法指定样式:

      With ThisDocument.Range.Find
          .Text = "The Heading"
          .Format = true   <<< -------- Tells Word to look for a special formatting
          .Style = ThisDocument.Styles("Heading 1")
      
          Do
              blnFound = .Execute
              If blnFound Then
                 Debug.Print "Found"
              Else
                 Exit Do
              End If
          Loop
      End With
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-16
        • 1970-01-01
        • 1970-01-01
        • 2017-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多