VBA - WORD 删除特定单词前后的行 [英] VBA - WORD Deleting rows after and before specific word

查看:63
本文介绍了VBA - WORD 删除特定单词前后的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 VBA 清理我的 Word 文档.

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

某处发生了一些事情!

website.com 08.01.2019

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.

标记重要的东西

该网站 99% 的情况下不会显示在第一行,所以我试图找到第二行.我想保留其他网站和文本(所以它会跳过 newsbetter.com)在每个文档中,大约有 30-100 个字样,就像我之前输入的(那些确实删除了)

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)

我一直在互联网上搜索可能的解决方案,但它们通常用于 Excel.我认为字符串在这里对我不起作用.

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

我希望结果会删除整个段落,但它只是删除了一行并保留了其他行.我需要一些指示,因为我是 VBA 新手.

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.

推荐答案

以下代码根据问题中的示例,从文档的开头到结尾搜索术语.一经发现,该词前后的段落将被删除.然后将搜索Range 设置为在找到的实例之后 的文档内容,以便不会重复选取相同的实例.

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.

请注意,我包含了 Find.Wrap = wdFindStop 以防止代码再次循环遍历文档.还需要在循环内重复 Execute 方法,而不是尝试在其上循环.While...Wend 是一种老式的循环;首选是 Do While...Loop.

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

这篇关于VBA - WORD 删除特定单词前后的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆