Slik automatiserer du Microsoft Word ved hjelp av Visual Basic for å opprette et nytt dokument

Sammendrag

Denne trinnvise artikkelen beskriver hvordan du oppretter et nytt dokument i Word ved hjelp av automatisering fra Visual Basic.

Eksempelkode

Eksempelkoden i denne artikkelen demonstrerer hvordan du gjør følgende:

  • Sett inn avsnitt med tekst og formatering.
  • Bla gjennom og endre ulike områder i et dokument.
  • Sett inn tabeller, formater tabeller og fyll ut tabellene med data.
  • Legg til et diagram.

Hvis du vil opprette et nytt Word-dokument ved hjelp av automatisering fra Visual Basic, gjør du følgende:

  1. Opprett et nytt Standard EXE-prosjekt i Visual Basic. Skjema1 er opprettet som standard.

  2. KlikkReferanserProsjekt-menyen, klikk ett av følgende alternativer, og klikk deretter OK:

    • For Office Word 2007 klikker du Microsoft Word 12.0-objektbibliotek.
    • For Word 2003 klikker du Microsoft Word 11.0-objektbibliotek.
    • For Word 2002 klikker du Microsoft Word 10.0-objektbibliotek.
    • Klikk Microsoft Word 9.0-objektbibliotek for Word 2000.
  3. Legg til en CommandButton-kontroll i Skjema1.

  4. Legg til følgende kode i Klikk-hendelsen for Kommando1:

     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
    
    
  5. Trykk F5 for å kjøre programmet, og klikk deretter Kommando1.

Når koden er fullført, kan du undersøke dokumentet som ble opprettet for deg. Dokumentet inneholder to sider med formaterte avsnitt, tabeller og et diagram.

Bruke en mal

Hvis du bruker automatisering til å bygge dokumenter som alle er i et felles format, kan du dra nytte av å starte prosessen med et nytt dokument som er basert på en forhåndsformatert mal. Bruk av en mal med Word Automation-klienten har to betydelige fordeler ved å bygge et dokument fra ingenting:

  • Du kan ha større kontroll over formateringen og plasseringen av objekter i hele dokumentene.
  • Du kan bygge dokumenter med mindre kode.

Ved hjelp av en mal kan du finjustere plasseringen av tabeller, avsnitt og andre objekter i dokumentet, samt inkludere formatering på disse objektene. Ved hjelp av automatisering kan du opprette et nytt dokument basert på malen med kode, for eksempel følgende:

oWord.Documents.Add "<Path to your template>\MyTemplate.dot"

I malen kan du definere bokmerker slik at automatiseringsklienten kan fylle ut variabel tekst på et bestemt sted i dokumentet, som følger:

oDoc.Bookmarks("MyBookmark").Range.Text = "Some Text Here"

En annen fordel med å bruke en mal er at du kan opprette og lagre formateringsstiler som du vil bruke ved kjøring, som følger:

oDoc.Bookmarks("MyBookmark").Range.Style = "MyStyle"

eller

oWord.Selection.Style = "MyStyle"

Referanser

Hvis du vil ha mer informasjon, klikker du artikkelnumrene nedenfor for å vise artiklene i Microsoft Knowledge Base:

285332 Hvordan automatisere Word 2002 med Visual Basic for å opprette en utskriftsfletting

Microsoft Office Development med Visual Studio

(c) Microsoft Corporation 2001, med enerett. Bidrag fra Lori B. Turner, Microsoft Corporation.