VBA - WORD Deleting rows after and before specific word

限于喜欢 提交于 2021-02-11 14:15:06

问题


I'm trying to clean up my Word document using VBA.

What i need to do is to find a specific word (usually a website) then select the line it is in and then select and then remove text line above(only 1 line), the lines under that website line as well (sometimes more than 2 - if the text is longer). I'll try to show you how the line looks now.

Something happend at someplace!

website.com 08.01.2019

Something happend at someplace and it was a bad person doing it. He used spaces instead of tabs in his code.

TAG-important stuff


The website 99% of times doesn't show in the 1st line, so im trying to find the 2nd line. There are other websites and texts i would like to keep (so it would skip newsbetter.com) In every document there are about 30-100 pharagraphs like the one I've typed earlier (the ones do delete)

I've been searching on the internet for a possible solution but they usually are for Excel. I think that strings are not working for me here.

Sub ScratchMacroII()
Dim oRng As Word.Range
Set oRng = ActiveDocument.Range
With oRng.Find
  .Text = "news.pl"
  While .Execute
    While oRng.Find.Found
        oRng.Select
        Selection.Expand Unit:=wdParagraph
        Selection.Delete
     Wend
End With
End Sub

I expected the result to delete the whole pharagraph, but it justs deletes one line and leaves the other ones. I need some pointers since I'm new at VBA.


回答1:


The following code, based on the sample in the question, searches the term from the beginning to the end of the document. When found, the paragraphs following and preceding the term are deleted. The search Range is then set to the document content following the found instance so that the same instance is not picked up repeatedly.

Note that I included Find.Wrap = wdFindStop to prevent the code from cycling through the document again. It's also necessary to repeat the Execute method within the loop, rather than trying to loop on it. While...Wend is an old type of loop; preferred is Do While...Loop.

Sub ScratchMacroII()
Dim oRng As Word.Range
Dim para As Word.Paragraph
Dim found As Boolean

Set oRng = ActiveDocument.Range
With oRng.Find
  .Text = "news.pl"
  .wrap = wdFindStop
  found = .Execute
    Do While found
        Set para = oRng.Next(wdParagraph, 1).Paragraphs(1)
        para.Range.Delete
        Set para = oRng.Next(wdParagraph, -1).Paragraphs(1)
        para.Range.Delete
        oRng.Collapse wdCollapseEnd
        oRng.End = ActiveDocument.content.End
        found = oRng.Find.Execute
     Loop

End With
End Sub


来源:https://stackoverflow.com/questions/56884018/vba-word-deleting-rows-after-and-before-specific-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!