Microsoft Word VBA通​​配符字符串

时间:2018-01-24 17:37:28

标签: vba ms-word wildcard boolean-logic

长话短说我使用的脚本突出显示使用某种格式的单词,然后将它们导出为ex​​cel。我似乎无法使用Word内置的通配符系统来获取我正在寻找的结果(我对它不是很熟悉),但我很接近!

我希望提取内联某种格式的定义:

这是您("乐于助人"或" HP")使用的示例文本("示例"),这个"应该是"可能的。

我的字符串应该捕获样本,有用的人和HP以上(但不是"应该是")。也就是说括号内的引号中的所有文字。

目前,我可以通过以下方式设置智能或直线引号之间的所有内容:

    (" & ChrW(8220) & ")(*)(" & ChrW(8221) & ") 

[字符数字用于有角度的引号]

这当然会返回引号中的字符串,即使这些引号没有嵌套在括号中。

有人能让我走上正轨吗?非常感谢!

请注意,脚本的其余部分使用MSwords通配符系统,不是正则表达式,因此更改为正则表达式:(。

此处的完整脚本只会突出显示与字符串匹配的字词:

Sub findfunction()
  If (findHL(ActiveDocument.Content, "(" & ChrW(8220) & ")(*)(" & ChrW(8221) & ")")) = True Then _
     MsgBox "Done", vbInformation + vbOKOnly, "Result"
End Sub

Function findHL(r As Range, s As String) As Boolean
  Options.DefaultHighlightColorIndex = wdYellow
  r.Find.Replacement.Highlight = True
  r.Find.Execute FindText:=s, MatchWildcards:=True, _
                 Wrap:=wdFindContinue, Format:=True, _
                 replacewith:="", Replace:=wdReplaceAll
  findHL = True
End Function

再次感谢。

2 个答案:

答案 0 :(得分:0)

也许在你的潜艇中运行你的功能两次:

Sub findfunction()
  found = False
  If findHL(ActiveDocument.Content, [wildcard string for condition A]) = True Then found = True
  If findHL(ActiveDocument.Content, [wildcard string for condition B]) = True Then found = True
  If found = True Then MsgBox "Done", vbInformation + vbOKOnly, "Result"
End Sub

虽然

,但我看不出它是如何导出到Excel的

答案 1 :(得分:0)

以下适用于我。但我不相信它可以通过“简单”的查找/替换来完成。我要做的就是找到每个实例,然后向后“走”范围以查看我是否能找到一个左括号,然后转发以找到一个右括号 - 总是检查没有中间的结束。存在括号。只有这样才能应用突出显示。

为了做到这一点,需要三个单独的Range对象:一个用于搜索,一个用于找到的范围,一个用于测试向后/向前。

Sub findfunction()
  If (findHL(ActiveDocument.content, _
      "(" & ChrW(8220) & ")(*)(" & ChrW(8221) & ")")) = True Then
     MsgBox "Done", vbInformation + vbOKOnly, "Result"
  End If
End Sub

Function findHL(r As Range, s As String) As Boolean
    Dim success As Boolean
    Dim foundRange As word.Range
    Dim testRange As word.Range
    Dim moved As Long

  success = False
  Set foundRange = r.Duplicate
  Options.DefaultHighlightColorIndex = wdYellow
  r.Find.Replacement.Highlight = True
  Do
    success = foundRange.Find.Execute(findText:=s, MatchWildcards:=True, _
                 wrap:=wdFindStop, Format:=True)
    If success Then
        r.Start = foundRange.End
        Set testRange = foundRange.Duplicate
        moved = testRange.MoveStartUntil("()", wdBackward)
        If moved < 0 Then
            testRange.MoveStart wdCharacter, -1
            If Left(testRange, 1) = "(" Then
                moved = testRange.MoveEndUntil(")", wdForward)
                If moved > 0 Then
                    testRange.MoveEnd wdCharacter, 1
                    If Right(testRange, 1) = ")" Then
                      foundRange.HighlightColorIndex = wdYellow
                    End If
                End If
            End If
        End If
    End If
  Loop While success = True
  findHL = True
End Function