2014-01-16 35 views
2

我試圖創建一個宏以查找特定表達式並刪除該內容。 例如,我需要刪除從「通知」一詞到「早上好」這個詞的所有內容(但如果可能的話,請保留「早上好」。)選擇文本並將其刪除的代碼

我有一段代碼可以刪除一行,但不能因爲我每次都沒有相同數量的線,可能是3或者最多9,或多或少。

我的代碼是這樣的移除這樣做並不與此問題相關的其他事情,我有)的代碼部分:

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 

誰能賜教

回答

0

這就是你想要的(根據我的理解)。只需將該函數粘貼到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)將返回在該String2是內部String1

找到位置
相關問題