0
votes

I've been going through the forums, but I'm unable to best match to get i wanna do.

I wanna copy a after searching for a keyword, e.g. Find ( Apple ) then select copy everything of it for the next few paragraphs and stop the range before the next word ( AppleEnd)

I tried this initially,

  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)

However i get an Object error code

Hence i tried this method

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

The second one im getting error about While error, how to i put a stop to it? or how can i replace it?

Which is better between the two

Appreciate the guidance.

1
A tip for you: when you get an error cite the full error message AND specifiy which line of code triggered it. Also, if an Answer works for you, click the checkmark to its left to mark it as "The Answer". That will help others as well as the person who helped you. Any "Answer" you find useful should be up-voted.Cindy Meister

1 Answers

0
votes

To Find all of:

( Apple ) then select copy everything of it for the next few paragraphs and stop the range before the next word ( AppleEnd)

simply use a wildcard Find, where:

Find = (( Apple)*\1End)

Similarly, for your 'SLHT ... SLHTEND' range, use:

Find = (SLHT)*\1END

In code, that might look like:

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

Note that wildcard Finds are case-sensitive.