Microsoft로 로그인
로그인하거나 계정을 만듭니다.
안녕하세요.
다른 계정을 선택합니다.
계정이 여러 개 있음
로그인할 계정을 선택합니다.

이 문서의 Microsoft Visual C# .NET 버전은 316384 참조하세요.
 

이 문서의 Microsoft Visual Basic 6.0 버전은 313193 참조하세요.
 

요약

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

샘플 코드

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

  • 텍스트 및 서식이 있는 단락을 삽입합니다.

  • 문서 내의 다양한 범위를 찾아보고 수정합니다.

  • 테이블을 삽입하고, 테이블에 서식을 지정하고, 데이터를 사용하여 테이블을 채웁니다.

  • 차트를 추가합니다.

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

  1. Microsoft Visual Studio .NET을 시작합니다. 파일 메뉴에서 새로 만들기를 클릭한 다음 프로젝트를 클릭합니다. 프로젝트 유형에서 Visual Basic Projects를 클릭한 다음 템플릿 아래에서 Windows 애플리케이션을 클릭합니다. Form1은 기본적으로 만들어집니다.

  2. Microsoft Word 개체 라이브러리에 대한 참조를 추가합니다. 이렇게 하려면 다음과 같이 하십시오.

    1. 프로젝트 메뉴에서 참조 추가를 클릭합니다.

    2. COM 탭에서 Microsoft Word 개체 라이브러리를 찾아 선택을 클릭합니다.

      참고 Microsoft Office 2003 이상 버전의 Office에는 기본 Interop 어셈블리(PIA)가 포함됩니다. Microsoft Office XP에는 PIA가 포함되지 않지만 다운로드할 수 있습니다.
       

    3. 참조 추가 대화 상자에서 확인을 클릭하여 선택을 수락합니다. 선택한 라이브러리에 대한 래퍼를 생성하라는 메시지가 표시되면 예를 클릭합니다.

  3. 보기 메뉴에서 도구 상자를 선택하여 도구 상자를 표시한 다음 Form1에 단추를 추가합니다.

  4. Button1을 두 번 클릭합니다. 양식의 코드 창이 나타납니다.

  5. 코드 창에서 다음 코드를 바꿉

        Private Sub Button1_Click(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles Button1.Click
    
        End Sub

    을 사용하여 다음을 수행합니다.

        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
  6. Form1.vb의 맨 위에 다음 코드를 추가합니다.

    Imports Word = Microsoft.Office.Interop.Word
  7. F5 키를 눌러 프로그램을 빌드하고 실행합니다.

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

템플릿 사용

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

  • 문서 전체에서 개체의 서식 및 배치를 보다 잘 제어할 수 있습니다.

  • 적은 코드로 문서를 빌드할 수 있습니다.

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

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

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

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

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

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

-또는-

oWord.Selection.Style = "MyStyle"

참고 자료

Visual Basic .NET을 사용하여 Microsoft Word를 자동화하는 방법에 대한 자세한 내용은 다음 문서 번호를 클릭하여 Microsoft 기술 자료의 문서를 확인합니다.

301656 Word를 자동화하여 Visual Basic .NET에서 편지 병합을 수행하는 방법

도움이 더 필요하세요?

더 많은 옵션을 원하세요?

구독 혜택을 살펴보고, 교육 과정을 찾아보고, 디바이스를 보호하는 방법 등을 알아봅니다.

커뮤니티를 통해 질문하고 답변하고, 피드백을 제공하고, 풍부한 지식을 갖춘 전문가의 의견을 들을 수 있습니다.

이 정보가 유용한가요?

언어 품질에 얼마나 만족하시나요?
사용 경험에 어떠한 영향을 주었나요?
제출을 누르면 피드백이 Microsoft 제품과 서비스를 개선하는 데 사용됩니다. IT 관리자는 이 데이터를 수집할 수 있습니다. 개인정보처리방침

의견 주셔서 감사합니다!

×