How to: Programmatically Add Shapes to a Visio Document


You can add shapes to a Microsoft Office Visio document by retrieving the masters from a stencil and dropping the shapes on the active page.

For more information, see the VBA reference documentation for the Microsoft.Office.Interop.Visio.Documents.Add method, Microsoft.Office.Interop.Visio.Application.ActivePage property, and Microsoft.Office.Interop.Visio.Page.Drop method.

To add shapes to a Visio document

  • With a document active, retrieve the masters from the Documents.Masters collection and drop the shapes on the active document. You can retrieve a master by using the index or master name.

    The following code example creates a blank Visio document, and then opens it with the Basic Shapes stencil docked. The code then retrieves several shapes and drops them on the active page.

    Visio.Documents visioDocs = this.Application.Documents;
    Visio.Document visioStencil = visioDocs.OpenEx("Basic Shapes.vss",
    Visio.Page visioPage = this.Application.ActivePage;
    Visio.Master visioRectMaster = visioStencil.Masters.get_ItemU(@"Rectangle");
    Visio.Shape visioRectShape = visioPage.Drop(visioRectMaster, 4.25, 5.5);
    visioRectShape.Text = @"Rectangle text.";
    Visio.Master visioStarMaster = visioStencil.Masters.get_ItemU(@"Star 7");
    Visio.Shape visioStarShape = visioPage.Drop(visioStarMaster, 2.0, 5.5);
    visioStarShape.Text = @"Star text.";
    Visio.Master visioHexagonMaster = visioStencil.Masters.get_ItemU(@"Hexagon");
    Visio.Shape visioHexagonShape = visioPage.Drop(visioHexagonMaster, 7.0, 5.5);
    visioHexagonShape.Text = @"Hexagon text.";