代码来select文本并将其删除

我正在尝试创build一个macros来查找特定的expression式并删除该内容。 例如,我需要删除从“通知”一词到“早上好”(但是如果可能,保持“早上好”)的所有内容。

我有一个代码删除一行,但不知道如何做一个select,因为我没有相同的行数每次。 可能是3或9,或多或less。

我有这样的代码是这样的(我已经删除了代码,做了其他事情,这与我有这个问题没有关系的部分):

Private Sub ProcessMsg(msg As MailItem) On Error GoTo ErrorHandlerProcessMsg Dim msg2 As Outlook.MailItem Dim msgDoc As Word.Document Dim msgDoc2 As Word.Document Dim objSel As Word.Selection Set msg2 = Application.CreateItem(olMailItem) Set msgDoc = msg.GetInspector.WordEditor Set msgDoc2 = msg2.GetInspector.WordEditor msgDoc.Select msgDoc.Windows(1).Selection.Copy msgDoc2.Windows(1).Selection.PasteAndFormat wdPasteDefault Set objSel = msgDoc2.Windows(1).Selection With objSel .Find.Execute "NOTIFICATION" .Collapse wdCollapseStart .MoveEnd WdUnits.wdStory, 1 .Delete End With Set objSel = msgDoc2.Windows(1).Selection With objSel .MoveStart WdUnits.wdStory, -1 .Collapse wdCollapseStart .MoveEnd WdUnits.wdParagraph, 1 .Delete End With Set msgDoc = Nothing Set msgDoc2 = Nothing Set objSel = Nothing Set msg2 = Nothing Exit Sub ErrorHandlerProcessMsg: Set msgDoc = Nothing Set msgDoc2 = Nothing Set objSel = Nothing Set msg2 = Nothing Err.Raise Err.Number, Err.Source, Err.Description End Sub 

谁能开导我吗?

这就是你想要的(从我的理解)。 只需将这个函数粘贴到word文档的代码对象中,然后运行它(尝试过Word而不是Excel)。 主要是向你展示如何处理这样的问题。

 Sub LineRemover() Dim doc As Document Set doc = ActiveDocument Dim myParagraph As Paragraph Dim mySentences As Sentences Dim mySentence As Range Dim deleted As Boolean deleted = False For Each myParagraph In doc.Paragraphs Set mySentences = myParagraph.Range.Sentences For Each mySentence In mySentences If InStr(mySentence, "Good morning") <> 0 Then '"Good morning" is present inside this line; exit the loop! Exit For ElseIf deleted Then '"NOTIFICATION" was already deleted, need to remove all subsequent lines! mySentence.Delete ElseIf InStr(mySentence, "NOTIFICATION") <> 0 Then '"NOTIFICATION" is present inside this line; delete it! mySentence.Delete deleted = True 'Tell the program you've deleted it! End If Next If deleted Then Exit For End If Next End Sub 

额外的细节: InStr(String1, String2)将返回在String1findString1