1

I've written this code in an attempt to first locate a string, or set of strings specified by the end-user. After finding the string the code will ask whether the user wants to in fact modify the content. If the user selects yes, it will then prompt the question of how many paragraphs including current paragraphs and after the found string, does the user want to delete.

I can't seem to get it to not simply delete the paragraphs from the beginning of the document. Is there anything I can do to achieve the function I need?

Thanks in advance!

This is MS Word VBA code.

Sub DeleteParagraphs_INPROCESS()
  Dim strFindTexts As String
  Dim strButtonValue As String
  Dim nSplitItem As Long
  Dim objDoc As Document
  Dim pcnt As Long


  strFindTexts = InputBox("Enter texts to be found here, and use commas to 
separate them: ", "Texts to be found", "SNP, POS")
  nSplitItem = UBound(Split(strFindTexts, ","))
  With Selection
    .HomeKey Unit:=wdStory

    ' Find the entered texts one by one.
    For nSplitItem = 0 To nSplitItem
      With Selection.Find
        .ClearFormatting
        .Text = Split(strFindTexts, ",")(nSplitItem)
        .Replacement.Text = ""
        .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchWholeWord = False
    .MatchCase = False
    .MatchSoundsLike = False
    .MatchWildcards = False
    .MatchAllWordForms = False
    .Execute
  End With

  Do While .Find.Found = True
    strButtonValue = MsgBox("Delete the content?", vbYesNoCancel)
    If strButtonValue = vbYes Then
    pcnt = InputBox("How many paragraphs need to be deleted?", "Number of subsequent paragraphs:", "")
   ActiveDocument.Paragraphs(pcnt).Range.Select
   Selection.Delete

    End If
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
Next
  End With


      MsgBox ("Finished finding all entered texts.")
      Set objDoc = Nothing
    End Sub

Expected result: Deleting paragraphs, including the string and subsequent paragraphs according to what the user specifies in the input box, and not simply deleting paragraphs at the beginning of the document.

Rich Michaels
  • 1,663
  • 2
  • 12
  • 18
  • There have been several recent questions involving the use of find that can help you, e.g. https://stackoverflow.com/a/56622629/5211752 – Timothy Rylatt Jun 22 '19 at 06:27
  • Instead of 'ActiveDocument.Paragraphs(pcnt).Range.Select: Selection.Delete' You should extend the current found range by the number of required paragraphs ('.Moveend(unit:=wdparagraph,count=pcnt') then just '.delete' to delete the current extended found range. – freeflow Jun 22 '19 at 08:19

2 Answers2

0

Chnage the Do-loop to set a Rangeobject to the paragraph in which the found item exists, then extend that for the number of paragraph specified (minus 1 for the current paragraph). For example:

  Do While .Find.found = True
    strButtonValue = MsgBox("Delete the content?", vbYesNoCancel)
    If strButtonValue = vbYes Then
        pcnt = InputBox("How many paragraphs need to be deleted?", "Number of subsequent paragraphs:", "")
        Dim rng As Range
        Set rng = Selection.Paragraphs(1).Range
        rng.MoveEnd wdParagraph, pcnt - 1            
        rng.Delete
    End If
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop

Note 1 If Range.Find were used instead of Selection.Find declaring and setting the Range in the loop would be unnecessary.

Note 2 You should change wdFindContinue for the wrap property to wdFindStop. There's always the danger, when using Find in VBA, that it enters an endless loop, repeatedly rechecking the document from the beginning. So it's a good idea to get into the habit of using wdFindStop.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
0

The issue you mention in your question is being caused by this statement:

ActiveDocument.Paragraphs(pcnt).Range.Select

It is an absolute statement saying select a specific paragraph in the document. If the value of pcnt is 2, then it will select the 2nd paragraph in the document. What you should be doing is selecting the paragraphs that follow the paragraph in which the text string was found.

There are two other issues in your code.

The first is the placement of the .HomeKey Unit:=wdStory command. Because you want to search the entire document for each individual text string, you have to return to the top of the document for each new string search.

The other issue is that your code assumes the user always wants to delete additional paragraphs. What if they only want to delete the paragraph that contains the located text string? You don't have a provision for that case.

Below is your code revised and I've added some comments. You might want to study what I have done.

Sub DeleteParagraphs_INPROCESS()
    Dim strFindTexts As String
    Dim strButtonValue As String
    Dim nSplitItem As Long
    Dim objDoc As Document
    Dim pcnt As Long

    strFindTexts = InputBox("Enter texts to be found here, and use commas to separate them: ", "Texts to be found", "SNP, POS")
    nSplitItem = UBound(Split(strFindTexts, ","))
    With Selection
'        .HomeKey Unit:=wdStory 'moved this down
        ' Find the entered texts one by one.
        For nSplitItem = 0 To nSplitItem
            .HomeKey Unit:=wdStory 'must be here in order to search the entire document for each text string
            With Selection.Find
                .ClearFormatting
                .Text = Split(strFindTexts, ",")(nSplitItem)
                .Replacement.Text = ""
                .Forward = True
                .Wrap = wdFindContinue
                .Format = False
                .MatchWholeWord = False
                .MatchCase = False
                .MatchSoundsLike = False
                .MatchWildcards = False
                .MatchAllWordForms = False
                .Execute
            End With
            Do While .Find.found = True
                strButtonValue = MsgBox("Delete the content?", vbYesNoCancel)
                If strButtonValue = vbYes Then
                    Selection.Range.Paragraphs(1).Range.Select
                    pcnt = InputBox("How many paragraphs need to be deleted?", "Number of subsequent paragraphs:", "")
                    'ActiveDocument.Paragraphs(pcnt).Range.Select 'this will always delete the 2nd paragraph in the document
                    If pcnt = 0 Then 'what if they don't want to delete subsequent paragraphs? You have to allow for that.
                        Selection.Delete
                    Else
                        Selection.MoveEnd wdParagraph, pcnt
                        Selection.Delete
                    End If
                End If
                .Collapse wdCollapseEnd
                .Find.Execute
            Loop
        Next
    End With
    MsgBox ("Finished finding all entered texts.")
    Set objDoc = Nothing
End Sub
Rich Michaels
  • 1,663
  • 2
  • 12
  • 18