Search code examples
c#ms-wordoffice-interopcom-interop

Word Interop- Add new autotext/building block


I need to update a bunch of values that are currently stored in multiple word documents as Auto Text (or Building Blocks), there are too many to do by hand so I was hoping to use the Interop Word API.

var app = new Application();
var doc = app.Documents.Open(@"c:\path\to\file.dot");

Unfortunately I cannot see any members of Document related to the Auto Text feature in Word (Insert > Quick Parts > Building Blocks Organizer).

Does the API expose any way of adding/updating Auto Text values in the 'Building Blocks Organizer'?


Solution

  • What you need to do is create a new document and attach the template to that document, from the top of my head:

    ActiveDocument.AttachedTemplate = @"C:\path\to\file.dot";

    After that you can interate over the AutoTextEntries like this (a VBA Example, but I'm sure you can rewrite it to C# quickly by yourself)

    Sub test()
    
        ActiveDocument.AttachedTemplate = @"C:\path\to\file.dot"
    
        For Each oAutoText In ActiveDocument.AttachedTemplate.AutoTextEntries
            MsgBox oAutoText.Value
            oAutoText.Value = Replace(oAutoText.Value, strOld, strNew)
        Next oAutoText
    
    End Sub