在Word表中重复选择字符串之间的文本

时间:2019-05-14 20:16:59

标签: vba ms-word

我已经构建了以下代码(略微来自stackoverflow answer

Sub findTest()
    Dim firstTerm As String
    Dim secondTerm As String
    Dim myRange As Range
    Dim documentText As String
    Dim startPos As Long 'Stores the starting position of firstTerm
    Dim stopPos As Long 'Stores the starting position of secondTerm based on first term's location
    Dim nextPosition As Long 'The next position to search for the firstTerm

    nextPosition = 1

    'First and Second terms as defined by your example.  Obviously, this will have to be more dynamic
    'if you want to parse more than justpatientFirstname.
    firstTerm = "<tag>"
    secondTerm = "</tag>"

    'Get all the document text and store it in a variable.
    Set myRange = ActiveDocument.Range
    'Maximum limit of a string is 2 billion characters.
    'So, hopefully your document is not bigger than that.  However, expect declining performance based on how big doucment is
    documentText = myRange '.Text

    'Loop documentText till you can't find any more matching "terms"
    Do Until nextPosition = 0
        startPos = InStr(nextPosition, documentText, firstTerm, vbTextCompare)
        stopPos = InStr(startPos, documentText, secondTerm, vbTextCompare)
        ActiveDocument.Range(Start:=startPos + Len(firstTerm), End:=stopPos - 1).Select ' = True
        Debug.Print Selection.Text
        nextPosition = InStr(stopPos, documentText, firstTerm, vbTextCompare)
    Loop
End Sub

在表的单元格内搜索和替换<tag></tag>之间的文本(我尚未实现替换操作)。 碰巧每个选择都会在右侧移动一些字符。 例如,如果我有:

| <tag>Bill</tag> | <tag>Steve</tag> | <tag>Mark</tag> |  

我进入控制台:

ill
eve<
k</t

我该如何解决?

1 个答案:

答案 0 :(得分:0)

在涉及表和/或字段的地方Instr不可靠。出于您的目的,请使用Word通配符查找,如下所示:

Sub Demo()
Application.ScreenUpdating = False
Dim StrOut As String
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "\<tag\>*\</tag\>"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    If .Information(wdWithInTable) = True Then
      StrOut = StrOut & vbCr & Split(Split(.Text, ">")(1), "<")(0)
    End If
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
Application.ScreenUpdating = True
MsgBox "Found:" & StrOut
End Sub