johhoso
johhoso

Reputation: 35

Generating replacement text from found text for Word addin, using VB.NET and Office-Interop

I need to add correct stress accents to every word in a Microsoft Word document. I have a script called "DoAccentuate" which determines the correct accentuation for any word that is input. However, I don't know how to capture the currently selected found word, process it with my DoAccentuate script, and replace that same word with the result (without effecting the formatting of the text). This is what I tried.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim document As Word.Document
    document = Globals.ThisAddIn.Application.ActiveDocument

    Dim FindObject As Word.Find = document.Application.Selection.Find
    With FindObject
        .ClearFormatting()
        .Text = "<*>"
        .MatchWildcards = True
        .Replacement.ClearFormatting()
        .Replacement.Text = DoAccentuate(document.Application.Selection.Text)
        .Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)

    End With
End Sub

Upvotes: 1

Views: 1224

Answers (1)

JohnZaj
JohnZaj

Reputation: 3230

Lets pretend for now this is your DoAccentuate script:

Private Function DoAccentuate(theWordToAccentuate As String)
    theWordToAccentuate = theWordToAccentuate + "`"
    DoAccentuate = theWordToAccentuate
End Function

Given this, the find/replace can be as simple as:

Public Sub FindWordAndReplaceWithAccentuatedForm()
    Dim accentuatedText As String: accentuatedText = DoAccentuate(Selection.text)

    Selection.Find.text = Selection.text
    Selection.Find.Replacement.text = DoAccentuate(Selection.text)
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

This should not remove any formatting.

I am assuming that you desire a solution which requires user to select the word they want to accentuate, and then run the macro (since your method above assumes this ie: .Replacement.Text = DoAccentuate(document.Application.Selection.Text

Upvotes: 1

Related Questions