在查找文本词之后选择一系列单词并在另一个第二个单词之前停止。 (之前和之后的范围)

时间:2018-03-09 12:13:36

标签: vba ms-word word-vba

我一直在浏览论坛,但我无法做到最好的匹配。

我想在搜索关键字后复制一个,例如查找(Apple)然后选择复制下一段中的所有内容并在下一个单词(AppleEnd)之前停止范围

我最初尝试过这个,

  Dim rng1 As Word.Range
  Dim rng2 As Word.Range
  Dim findthetext As String

If part12 = 1 Then

Set rng1 = ActiveDocument.Range
If rng1.Find.Execute(FindText:="SLHT") Then

Set rng2 = ActiveDocument.Range(rng1.End, ActiveDocument.Range.End)

If rng2 = Find.Execute(FindText:="SLHTEND") Then

findthetext = ActiveDocument.Range(rng1.End, rng2.Start).Text

 Selection.Copy

 Windows("Doc2").Activate

 Selection.PasteAndFormat (wdFormatOriginalFormatting)

但是我得到一个对象错误代码

因此我尝试了这种方法

Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim copyrange1 As Range
Dim copyrange2 As Range
Dim copyrange3 As Range



Dim findthetext As String


Set rng1 = ActiveDocument.Range
Set rng2 = ActiveDocument.Range
Set rng3 = ActiveDocument.Range



With rng1.Find
.Text = "SLCB"

 While .Execute
If Found = True Then
Set copyrange1 = rng1
copyrange1.Select

rng2.Start = copyrange1.End
rng2.End = ActiveDocument.Content.End

rng2.Select


 With rng2.Find
 .Text = "SLCBEND"

 If .Found = True Then
 Set copyrange3 = rng2
 copyrange3.Select

 End If
 End With


 rng3.Start = copyrange.Start
 rng3.End = copyrange3.End
 rng3.Select
 rng3.Copy

Windows("Doc2").Activate
Selection.PasteAndFormat (wdFormatOriginalFormatting)

 End If


End Sub

第二个我得到的错误虽然错误,我怎么停止它?或者我该如何更换它?

两者之间哪个更好

感谢指导。

1 个答案:

答案 0 :(得分:0)

查找全部:

(Apple)然后选择复制下一段中的所有内容并在下一个单词之前停止范围(AppleEnd)

只需使用通配符查找,其中:

Find =((Apple)* \ 1End)

同样,对于你的SLHT ...... SLHTEND'范围,使用:

查找=(SLHT)* \ 1END

在代码中,可能看起来像:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "(SLHT)*\1END"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  If .Find.Found = True Then
    MsgBox .Text
  End If
End With
Application.ScreenUpdating = True
End Sub

请注意,通配符Finds区分大小写。