Pour obtenir une version Microsoft Visual C# .NET de cet article, consultez 316384.
Pour obtenir une version Microsoft Visual Basic 6.0 de cet article, consultez 313193.
Résumé
Cet article pas à pas explique comment créer un document dans Word à l’aide d’Automation à partir de Visual Basic .NET.
Exemple de code
L’exemple de code de cet article montre comment effectuer les opérations suivantes :
-
Insérer des paragraphes avec du texte et une mise en forme.
-
Parcourir et modifier différentes plages au sein d’un document.
-
Insérez des tables, mettez en forme les tables et remplissez les tables avec des données.
-
Ajoutez un graphique.
Pour créer un document Word à l’aide d’Automation à partir de Visual Basic .NET, procédez comme suit :
-
Démarrez Microsoft Visual Studio .NET. Dans le menu Fichier, cliquez sur Nouveau, puis sur Projet. Sous Types de projets, cliquez sur Projets Visual Basic, puis sur Application Windows sous Modèles. Form1 est créé par défaut.
-
Ajoutez une référence à la bibliothèque d’objets Microsoft Word. Pour cela, procédez comme suit :
-
Dans le menu Projet, cliquez sur Ajouter une référence.
-
Sous l’onglet COM, recherchez la bibliothèque d’objets Microsoft Word, puis cliquez sur Sélectionner.
Remarque Microsoft Office 2003 et les versions ultérieures d’Office incluent les assemblys PIA (Primary Interop Assemblies). Microsoft Office XP n’inclut pas les pias, mais ils peuvent être téléchargés.
-
Cliquez sur OK dans la boîte de dialogue Ajouter des références pour accepter vos sélections. Si vous recevez une invite pour générer des wrappers pour les bibliothèques que vous avez sélectionnées, cliquez sur Oui.
-
-
Dans le menu Affichage, sélectionnez Boîte à outils pour afficher la Boîte à outils, puis ajoutez un bouton à Form1.
-
Double-cliquez sur Button1. La fenêtre de code du formulaire s’affiche.
-
Dans la fenêtre de code, remplacez le code suivant
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click End Sub
Avec:
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim oWord As Word.Application Dim oDoc As Word.Document Dim oTable As Word.Table Dim oPara1 As Word.Paragraph, oPara2 As Word.Paragraph Dim oPara3 As Word.Paragraph, oPara4 As Word.Paragraph Dim oRng As Word.Range Dim oShape As Word.InlineShape Dim oChart As Object Dim Pos As Double 'Start Word and open the document template. oWord = CreateObject("Word.Application") oWord.Visible = True oDoc = oWord.Documents.Add 'Insert a paragraph at the beginning of the document. oPara1 = oDoc.Content.Paragraphs.Add oPara1.Range.Text = "Heading 1" oPara1.Range.Font.Bold = True oPara1.Format.SpaceAfter = 24 '24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter() 'Insert a paragraph at the end of the document. '** \endofdoc is a predefined bookmark. oPara2 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range) oPara2.Range.Text = "Heading 2" oPara2.Format.SpaceAfter = 6 oPara2.Range.InsertParagraphAfter() 'Insert another paragraph. oPara3 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range) oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:" oPara3.Range.Font.Bold = False oPara3.Format.SpaceAfter = 24 oPara3.Range.InsertParagraphAfter() 'Insert a 3 x 5 table, fill it with data, and make the first row 'bold and italic. Dim r As Integer, c As Integer oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, 3, 5) oTable.Range.ParagraphFormat.SpaceAfter = 6 For r = 1 To 3 For c = 1 To 5 oTable.Cell(r, c).Range.Text = "r" & r & "c" & c Next Next oTable.Rows.Item(1).Range.Font.Bold = True oTable.Rows.Item(1).Range.Font.Italic = True 'Add some text after the table. 'oTable.Range.InsertParagraphAfter() oPara4 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range) oPara4.Range.InsertParagraphBefore() oPara4.Range.Text = "And here's another table:" oPara4.Format.SpaceAfter = 24 oPara4.Range.InsertParagraphAfter() 'Insert a 5 x 2 table, fill it with data, and change the column widths. oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, 5, 2) oTable.Range.ParagraphFormat.SpaceAfter = 6 For r = 1 To 5 For c = 1 To 2 oTable.Cell(r, c).Range.Text = "r" & r & "c" & c Next Next oTable.Columns.Item(1).Width = oWord.InchesToPoints(2) 'Change width of columns 1 & 2 oTable.Columns.Item(2).Width = oWord.InchesToPoints(3) 'Keep inserting text. When you get to 7 inches from top of the 'document, insert a hard page break. Pos = oWord.InchesToPoints(7) oDoc.Bookmarks.Item("\endofdoc").Range.InsertParagraphAfter() Do oRng = oDoc.Bookmarks.Item("\endofdoc").Range oRng.ParagraphFormat.SpaceAfter = 6 oRng.InsertAfter("A line of text") oRng.InsertParagraphAfter() Loop While Pos >= oRng.Information(Word.WdInformation.wdVerticalPositionRelativeToPage) oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd) oRng.InsertBreak(Word.WdBreakType.wdPageBreak) oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd) oRng.InsertAfter("We're now on page 2. Here's my chart:") oRng.InsertParagraphAfter() 'Insert a chart and change the chart. oShape = oDoc.Bookmarks.Item("\endofdoc").Range.InlineShapes.AddOLEObject( _ ClassType:="MSGraph.Chart.8", FileName _ :="", LinkToFile:=False, DisplayAsIcon:=False) oChart = oShape.OLEFormat.Object oChart.charttype = 4 'xlLine = 4 oChart.Application.Update() oChart.Application.Quit() 'If desired, you can proceed from here using the Microsoft Graph 'Object model on the oChart object to make additional changes to the 'chart. oShape.Width = oWord.InchesToPoints(6.25) oShape.Height = oWord.InchesToPoints(3.57) 'Add text after the chart. oRng = oDoc.Bookmarks.Item("\endofdoc").Range oRng.InsertParagraphAfter() oRng.InsertAfter("THE END.") 'All done. Close this form. Me.Close() End Sub
-
Ajoutez le code suivant en haut de Form1.vb :
Imports Word = Microsoft.Office.Interop.Word
-
Appuyez sur F5 pour générer et exécuter le programme.
Une fois le code terminé, examinez le document créé pour vous. Le document contient deux pages de paragraphes mis en forme, des tableaux et un graphique.
Utiliser un modèle
Si vous utilisez Automation pour générer des documents qui sont tous dans un format commun, vous pouvez tirer parti du démarrage du processus avec un nouveau document basé sur un modèle préformaté. L’utilisation d’un modèle avec votre client Word Automation présente deux avantages significatifs par rapport à la création d’un document à partir de rien :
-
Vous pouvez avoir un meilleur contrôle sur la mise en forme et le placement des objets dans vos documents.
-
Vous pouvez créer vos documents avec moins de code.
À l’aide d’un modèle, vous pouvez ajuster l’emplacement des tableaux, des paragraphes et d’autres objets dans le document, et inclure la mise en forme sur ces objets. À l’aide d’Automation, vous pouvez créer un document basé sur votre modèle avec du code tel que le suivant :
oWord.Documents.Add "<Path to your template>\MyTemplate.dot"
Dans votre modèle, vous pouvez définir des signets afin que votre client Automation puisse remplir le texte de variable à un emplacement spécifique dans le document, comme suit :
oDoc.Bookmarks.Item("MyBookmark").Range.Text = "Some Text Here"
Un autre avantage de l’utilisation d’un modèle est que vous pouvez créer et stocker les styles de mise en forme que vous souhaitez appliquer au moment de l’exécution, comme suit :
oDoc.Bookmarks.Item("MyBookmark").Range.Style = "MyStyle"
- ou -
oWord.Selection.Style = "MyStyle"
Références
Pour plus d’informations sur l’utilisation de Visual Basic .NET pour automatiser Microsoft Word, cliquez sur le numéro d’article suivant pour afficher l’article dans la Base de connaissances Microsoft :
301656 Comment automatiser Word pour effectuer un publipostage à partir de Visual Basic .NET