Visual Basic을 사용하여 새 문서를 만들어 Microsoft Word를 자동화하는 방법

요약

이 단계별 문서에서는 Visual Basic의 자동화를 사용하여 Word에서 새 문서를 만드는 방법을 설명합니다.

샘플 코드

이 문서의 샘플 코드는 다음을 수행하는 방법을 보여 줍니다.

  • 텍스트 및 서식이 있는 단락을 삽입합니다.
  • 문서 내의 다양한 범위를 찾아 수정합니다.
  • 테이블을 삽입하고, 테이블에 서식을 지정하고, 데이터를 사용하여 테이블을 채웁니다.
  • 차트를 추가합니다.

Visual Basic에서 Automation을 사용하여 새 Word 문서를 만들려면 다음 단계를 수행합니다.

  1. Visual Basic에서 새 표준 EXE 프로젝트를 만듭니다. Form1은 기본적으로 만들어집니다.

  2. 프로젝트 메뉴에서참조를 클릭하고 다음 옵션 중 하나를 클릭한 다음 확인을 클릭합니다.

    • Office Word 2007의 경우 Microsoft Word 12.0 개체 라이브러리를 클릭합니다.
    • Word 2003의 경우 Microsoft Word 11.0 개체 라이브러리를 클릭합니다.
    • Word 2002의 경우 Microsoft Word 10.0 개체 라이브러리를 클릭합니다.
    • Word 2000의 경우 Microsoft Word 9.0 개체 라이브러리를 클릭합니다.
  3. Form1에 CommandButton 컨트롤을 추가합니다.

  4. Command1의 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.
     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. F5 키를 눌러 프로그램을 실행한 다음 Command1을 클릭합니다.

코드가 완료되면 만들어진 문서를 검사합니다. 문서에는 서식이 지정된 단락, 표 및 차트의 두 페이지가 포함되어 있습니다.

템플릿 사용

Automation을 사용하여 모두 공통 형식의 문서를 빌드하는 경우 미리 서식이 지정된 템플릿을 기반으로 하는 새 문서로 프로세스를 시작하는 것이 도움이 될 수 있습니다. Word Automation 클라이언트에서 서식 파일을 사용하면 아무 작업도 수행하지 않은 문서 작성에 비해 두 가지 중요한 이점이 있습니다.

  • 문서 전체에서 개체의 서식 및 배치를 보다 세게 제어할 수 있습니다.
  • 적은 코드로 문서를 빌드할 수 있습니다.

서식 파일을 사용하면 문서 내의 표, 단락 및 기타 개체의 배치를 미세 조정할 수 있으며 해당 개체의 서식을 포함할 수 있습니다. Automation을 사용하면 다음과 같은 코드를 사용하여 템플릿을 기반으로 새 문서를 만들 수 있습니다.

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

템플릿에서 다음과 같이 Automation 클라이언트가 문서의 특정 위치에 변수 텍스트를 입력할 수 있도록 책갈피를 정의할 수 있습니다.

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

템플릿을 사용하는 또 다른 이점은 다음과 같이 런타임에 적용할 서식 스타일을 만들고 저장할 수 있다는 것입니다.

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

또는

oWord.Selection.Style = "MyStyle"

참조

자세한 내용은 아래 문서 번호를 클릭하여 Microsoft 기술 자료에서 문서를 확인합니다.

Visual Basic을 사용하여 Word 2002를 자동화하여 편지 병합을 만드는 방법 285332

Visual Studio를 사용한 Microsoft Office 개발

(c) Microsoft Corporation 2001, All Rights Reserved. 기여: 로리 비 터너, Microsoft Corporation.