Reputation: 4120
I'm playing around with VSTO, more precisely with C# and a "Microsoft Word" application add-in, at the moment. I do want to programmatically create nested fields. I've come up with the following source code (for testing purposes):
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, EventArgs e)
{
// TODO This is just a test.
this.AddDocPropertyFieldWithinInsertTextField("Author", ".\\\\FileName.docx");
}
private void AddDocPropertyFieldWithinInsertTextField(string propertyName, string filePath)
{
// TODO Horrible, since we rely on the UI state.
this.Application.ActiveWindow.View.ShowFieldCodes = true;
Word.Selection currentSelection = this.Application.ActiveWindow.Selection;
// Add a new DocProperty field at the current selection.
currentSelection.Fields.Add(
Range: currentSelection.Range,
Type: Word.WdFieldType.wdFieldDocProperty,
Text: propertyName,
PreserveFormatting: false
);
// TODO The following fails if a DocProperty with the specified name does not exist.
// Select the previously inserted field.
// TODO This is horrible!
currentSelection.MoveLeft(
Unit: Word.WdUnits.wdWord,
Count: 1,
Extend: Word.WdMovementType.wdExtend
);
// Create a new (empty) field AROUND the DocProperty field.
// After that, the DocProperty field is nested INSIDE the empty field.
// TODO Horrible again!
currentSelection.Fields.Add(
currentSelection.Range,
Word.WdFieldType.wdFieldEmpty,
PreserveFormatting: false
);
// Insert text BEFORE the inner field.
// TODO Horror continues.
currentSelection.InsertAfter("INCLUDETEXT \"");
// Move the selection AFTER the inner field.
// TODO See above.
currentSelection.MoveRight(
Unit: Word.WdUnits.wdWord,
Count: 1,
Extend: Word.WdMovementType.wdExtend
);
// Insert text AFTER the nested field.
// TODO See above.
currentSelection.InsertAfter("\\\\" + filePath + "\"");
// TODO See above.
this.Application.ActiveWindow.View.ShowFieldCodes = false;
// Update the fields.
currentSelection.Fields.Update();
}
Although the provided code covers the requirements, it has some major problems (as you can see if reading some of the code comments), e.g.:
I did some research on the WWW, but haven't been able to find a clean solution, yet.
So, my question is:
Upvotes: 3
Views: 1913
Reputation: 4120
I've created a generic implementation to create both non-nested and nested fields with VSTO for Microsoft Word. You can see the relevant source code in this Gist. I've ported the VBA source code from the article Nested Fields in VBA to C# and applied some improvements.
Still not perfect (needs some additional error handling), but far better than a solution with a Selection
object, which relies on the state of the user interface!
Upvotes: 1