2014-10-16 86 views
0

我想選擇 Ms Word通過VB.NET的特定單詞(Microsoft.Office.Interop.Word)。從MS Word通過VB.NET選擇詞

任何想法如何做到這一點?

編輯: 問題是我無法找到/替換字符串超過255個符號。這就是爲什麼我試圖找到這個問題的另一個解決方案。

+0

你有試過什麼嗎?如果是這樣,請發佈你的工作和你可能面臨的任何錯誤.. – 2014-10-16 14:45:49

+0

@Nadeem_MK,評論你的答案。 – Abdukhafiz 2014-10-16 20:39:54

回答

0

如果這個問題有人找解決辦法:

Imports Word = Microsoft.Office.Interop.Word 
Dim WordApp As Word.Application = New Word.Application 
Dim WordDoc As Word.Document 

Public Function FindReplaceText(CellsValueWithLabel As String()()) As Boolean 
    'Find and replace texts from arrays 
    For Each cellsValue In CellsValueWithLabel 
     Try 
      If cellsValue(1).Length < 255 Then 
       If WordDoc.Content.Find.Execute(FindText:=cellsValue(0), ReplaceWith:=cellsValue(1), Replace:=Word.WdReplace.wdReplaceAll) Then 
        logHistory.insertLogHistory(Chr(34) + cellsValue(0) + Chr(34) + " - replaced by " + Chr(34) + cellsValue(1) + Chr(34)) 
       End If 
      Else 
       Dim myRange = WordDoc.Content 
       While myRange.Find.Execute(FindText:=cellsValue(0)) 
        If myRange.Find.Found Then 
         myRange.Select() 
         My.Computer.Clipboard.SetText(cellsValue(1)) 
         WordApp.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault) 
         logHistory.insertLogHistory(Chr(34) + cellsValue(0) + Chr(34) + " - replaced by " + Chr(34) + cellsValue(1) + Chr(34)) 
         Clipboard.Clear() 
        End If 
       End While 
      End If 
     Catch ex As Exception 
      logHistory.insertLogHistory("********** ERROR ********** " + cellsValue(0) + " " + ex.Message.ToString()) 
     End Try 
    Next 

    WordDoc.Save() 
    Return True 
End Function 
0

你的問題似乎很模糊,但作爲一個開始,你可以按如下步驟進行;

 Dim objWord As New Word.Application 
     Dim WordToFind as string = "Test" 
     objWord.Visible = True 

     'Open an existing document. 
     Dim objDoc As Word.Document = objWord.Documents.Open("C:\folder\MyDoc.doc") 
     objDoc = objWord.ActiveDocument 

     'Find word 
     objDoc.Content.Find.Execute(FindText:=WordToFind) 

     ' perform your process with the searched text 

     'Close the document 
     objDoc.Close() 
     objDoc = Nothing 
     objWord.Quit() 
     objWord= Nothing 

希望它有幫助!

+0

感謝您的回答。我有相同的代碼。問題是我無法找到/替換超過255個符號的字符串。這就是爲什麼我試圖找到解決這個問題的另一種方式。 – Abdukhafiz 2014-10-16 20:38:13

+0

哦..可能你需要編輯你的問題並提及它;) – 2014-10-17 04:58:50

0

在情況下,它可以幫助任何人,以取代超過255個字符,使用範圍會有所幫助。

If (SomeText.Length < 250) Then 
    oSel.Find.Execute("SomeText", , , , , , True, Word.WdFindWrap.wdFindContinue, , "Replacetext", Word.WdReplace.wdReplaceAll) 
    Else 
     Dim rng As Word.Range = oSel.Range 
     rng.Find.Execute("SomeText", , , , , , , , , ,) 
     rng.Text = DirectCast(StringWithMoreThan255Characters, String) 

End If