Partilhar via


How to: Programmatically create new documents

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

When you create a document programmatically, the new document is a native Document object. This object does not have the additional events and data binding capabilities of a Document host item. For more information, see Programmatic limitations of host items and host controls.

Applies to: The information in this topic applies to document-level projects and VSTO Add-in projects for Word. For more information, see Features available by Office application and project type.

When you develop a document-level project, you cannot programmatically add Document host items to your project. In a VSTO Add-in project, you can convert any Document object to a Document host item at run time. For more information, see Extend Word documents and Excel workbooks in VSTO Add-ins at run time.

To create a new document based on the Normal template

  • Use the Add method of the Documents collection to create a new document based on the Normal template. To use this code example, run it from the ThisDocument or ThisAddIn class in your project.

    Me.Application.Documents.Add()
    
    this.Application.Documents.Add();
    

Use custom templates

The Add method has an optional Template argument to create a new document based on a template other than the Normal template. You must supply the file name and fully qualified path of the template.

To create a new document based on a custom template

  • Call the Add method of the Documents collection and specify the path to the template. To use this code example, run it from the ThisDocument or ThisAddIn class in your project.

    Me.Application.Documents.Add(Template:="C:\Test\SampleTemplate.dotx")
    
    this.Application.Documents.Add(@"C:\Test\SampleTemplate.dotx");
    

See also