Come automatizzare Microsoft Word usando Visual Basic per creare un nuovo documento
Riepilogo
Questo articolo dettagliato descrive come creare un nuovo documento in Word usando Automazione da Visual Basic.
Codice di esempio
Il codice di esempio in questo articolo illustra come eseguire le operazioni seguenti:
- Inserire paragrafi con testo e formattazione.
- Esplorare e modificare vari intervalli all'interno di un documento.
- Inserire tabelle, formattare le tabelle e popolare le tabelle con i dati.
- Aggiungere un grafico.
Per creare un nuovo documento di Word usando Automazione da Visual Basic, seguire questa procedura:
In Visual Basic creare un nuovo progetto EXE Standard. Form1 viene creato per impostazione predefinita.
Nel menu Progetto fare clic suRiferimenti, scegliere una delle opzioni seguenti e quindi fare clic su OK:
- Per Office Word 2007, fare clic su Libreria oggetti di Microsoft Word 12.0.
- Per Word 2003, fare clic su Libreria oggetti di Microsoft Word 11.0.
- Per Word 2002, fare clic su Libreria oggetti di Microsoft Word 10.0.
- Per Word 2000, fare clic su Libreria oggetti di Microsoft Word 9.0.
Aggiungere un controllo CommandButton a Form1.
Aggiungere il codice seguente all'evento Click per Command1:
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. Set oWord = CreateObject("Word.Application") oWord.Visible = True Set oDoc = oWord.Documents.Add 'Insert a paragraph at the beginning of the document. Set 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. Set oPara2 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks("\endofdoc").Range) oPara2.Range.Text = "Heading 2" oPara2.Format.SpaceAfter = 6 oPara2.Range.InsertParagraphAfter 'Insert another paragraph. Set oPara3 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks("\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,italic. Dim r As Integer, c As Integer Set oTable = oDoc.Tables.Add(oDoc.Bookmarks("\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(1).Range.Font.Bold = True oTable.Rows(1).Range.Font.Italic = True 'Add some text after the table. 'oTable.Range.InsertParagraphAfter Set oPara4 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks("\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. Set oTable = oDoc.Tables.Add(oDoc.Bookmarks("\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(1).Width = oWord.InchesToPoints(2) 'Change width of columns 1 & 2. oTable.Columns(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("\endofdoc").Range.InsertParagraphAfter Do Set oRng = oDoc.Bookmarks("\endofdoc").Range oRng.ParagraphFormat.SpaceAfter = 6 oRng.InsertAfter "A line of text" oRng.InsertParagraphAfter Loop While Pos >= oRng.Information(wdVerticalPositionRelativeToPage) oRng.Collapse (wdCollapseEnd) oRng.InsertBreak wdPageBreak oRng.Collapse wdCollapseEnd oRng.InsertAfter "We're now on page 2. Here's my chart:" oRng.InsertParagraphAfter 'Insert a chart and change the chart. Set oShape = oDoc.Bookmarks("\endofdoc").Range.InlineShapes.AddOLEObject( _ ClassType:="MSGraph.Chart.8", FileName _ :="", LinkToFile:=False, DisplayAsIcon:=False) Set 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. Set oRng = oDoc.Bookmarks("\endofdoc").Range oRng.InsertParagraphAfter oRng.InsertAfter "THE END." 'All done. Unload this form. Unload Me
Premere F5 per eseguire il programma e quindi fare clic su Comando1.
Al termine del codice, esaminare automaticamente il documento creato. Il documento contiene due pagine di paragrafi formattati, tabelle e un grafico.
Usare un modello
Se si usa Automazione per compilare documenti tutti in un formato comune, è possibile trarre vantaggio dall'avvio del processo con un nuovo documento basato su un modello preformattato. L'uso di un modello con il client di automazione di Word presenta due vantaggi significativi rispetto alla creazione di un documento dal nulla:
- È possibile avere un maggiore controllo sulla formattazione e il posizionamento degli oggetti in tutti i documenti.
- È possibile compilare i documenti con meno codice.
Usando un modello, è possibile ottimizzare il posizionamento di tabelle, paragrafi e altri oggetti all'interno del documento, nonché includere la formattazione su tali oggetti. Usando Automazione, è possibile creare un nuovo documento basato sul modello con codice simile al seguente:
oWord.Documents.Add "<Path to your template>\MyTemplate.dot"
Nel modello è possibile definire segnalibri in modo che il client di Automazione possa compilare testo variabile in una posizione specifica del documento, come indicato di seguito:
oDoc.Bookmarks("MyBookmark").Range.Text = "Some Text Here"
Un altro vantaggio dell'uso di un modello è la possibilità di creare e archiviare gli stili di formattazione che si desidera applicare in fase di esecuzione, come indicato di seguito:
oDoc.Bookmarks("MyBookmark").Range.Style = "MyStyle"
oppure
oWord.Selection.Style = "MyStyle"
Riferimenti
Per altre informazioni, fare clic sui numeri degli articoli seguenti per visualizzare gli articoli della Microsoft Knowledge Base:
285332 Come automatizzare Word 2002 con Visual Basic per creare una stampa unione
Sviluppo di Microsoft Office con Visual Studio
(c) Microsoft Corporation 2001, Tutti i diritti riservati. Contributi di Lori B. Turner, Microsoft Corporation.