2014-10-16 54 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