Reputation: 1096
How to delete certain sections that repeat in a word document. First section has word "example" and second section has word "example.com". If these strings are found delete entire section
Dim Sect As Section
For Each Sect In ActiveDocument.Sections
If ActiveDocument.Sect.Range.Find.Text = "example" Or ActiveDocument.Sect.Range.Find.Text ="example.com" Then
Activedocument.Sect.Range.delete
Next
Also start from section 5 in loop through entire word document
Upvotes: 0
Views: 1706
Reputation: 3435
You have several problems.
1) You aren't trying to start with Section 5, so it obviously won't do this. However, even if you were testing for this, your code would break because you are deleting sections and looping through forwards. You need to check the sections in reverse and then delete if they contain the string "example"
2) Your attempt at finding the strings won't work. It would have been nice if you had tried to run the code, noted the error that you had gotten while running it and stating the line that the error happened on. As is, this just doesn't make any sense. You could check the documentation on the find method if you'd like, but the InStr function will work better, as shown below.
3) When you use the construct, "For each Sect In ActiveDocument.Sections," the "Sect" variable BECOMES the section already. It knows what document it is in. "ActiveDocument.Sect...." will not work. You just need to use the Sect at that point. I have used a different way of looping, but the idea remains the same.
4) If you are already searching for the text "example" in a string, searching for the text "example.com" is pointless as "example" is already in the search string. Just do the one search.
<rant>
As I implied, please try to document the exact error and exact line of code that produces the error. While you have provided the code you "tried", you simply have not shown very much effort. When experiencing problems, I recommend that you debug by a) actually running the code and finding the error, b) seeing if there is an obvious syntax problem by doing research into the methods/properties you are trying to use and c) examining the variables using debug.print or the locals window to see if they contain what you think they do <\rant>
.
Working code below.
Sub test()
Dim mysects As Sections
Dim mysect As Section
Set mysects = ActiveDocument.Sections
For x = mysects.Last.Index To 5 Step -1
Set mysect = mysects.Item(x)
If InStr(1, mysect.Range.Text, "example", vbTextCompare) _
Or InStr( 1, mysect.Range.Text, "nextText", vbTextCompare) Then
mysect.Range.Delete
End If
Next x
End Sub
Upvotes: 1