通过VB.NET从MS Word中选择单词

时间:2014-10-16 14:06:22

标签: vb.net ms-word office-interop

我想通过VB.NET Microsoft.Office.Interop.Word 从 选择特定单词。

知道该怎么做吗?

编辑: 问题是我找不到/替换超过255个符号的字符串。这就是为什么我正在尝试为这个问题寻找另一种解决方案。

3 个答案:

答案 0 :(得分: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 

希望它有所帮助!

答案 1 :(得分: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

答案 2 :(得分: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