I created a Quick Table as a table template in my template dotx. I would like to create a Quick Table programmatically. is that possible?
Currently I use an existing table as template and copy its properties to the new table (see code).
object oTemplate = "D:\\Templates\\tables.dotx";
Word._Document doc = word.Documents.Add(oTemplate, ref oMissing, ref oMissing, ref oMissing);
// Copy first table as template
Word.Table tableTemplate = doc.Tables[1];
Word.Range rangeCopy = tableTemplate.Range;
rangeCopy.Copy();
...
// Reuse table template for new tables
object oMissing = Missing.Value;
var newTable = doc.Tables.Add(range, 1, 1, ref oMissing, ref oMissing);
newTable.Range.Paste();
The problem is that the dummy table is not deleted by the pasting, but moved downwards.
Solution:
var template = (Word.Template)doc.get_AttachedTemplate();
Word.BuildingBlock objBB = template.BuildingBlockEntries.Item("MyCustomBlock");
objBB.Insert(range, true);
The "Quick Tables" in the Insert > Table > Drop Down > Quick Table
list are Building Blocks. They can also be found in Insert > Text > Quick Parts > Building Block Organizer
, in the Tables gallery. This means these tables are stored in the user profile's Building Blocks template and should be part of a standard installation.
The basic (VBA) code to insert a built-in (installed as part of Office) Building Block is:
Application.Templates( _
"C:\Users\[user name]\AppData\Roaming\Microsoft\Document Building Blocks\1033\14\Built-In Building Blocks.dotx" _
).BuildingBlockEntries("Calendar 2").Insert Where:=Selection.Range, _
RichText:=True
And for C#
Word.Template objTmpl = wdApp.Templates[@"C:\Users\[user name]\AppData\Roaming\Microsoft\Document Building Blocks\1033\14\Built-In Building Blocks.dotx"];
Word.BuildingBlock objBB = objTmpl.BuildingBlockEntries.Item("Calendar 2");
objBB.Insert(rng, true);
If it's uncertain that this template will have been installed, or installed to a specific file path, then the more certain approach would be to save the table as a Building Block in the template being distributed as part of VSTO solution. That's simply a matter of selecting the table then using Insert > Text > Quick Parts > Save selection to Quick Part Gallery
. In the dialog box be sure to select the template from the Save in
list as the default could well be the installation template with the building blocks.
To insert a Building Block in the template from which a document was created (the "attached template"):
Word.Template objTmpl = (Word.Template)doc.get_AttachedTemplate();