Visual Basic에서 Word를 자동화하여 우편물 레이블에 대한 편지 병합을 만드는 방법

요약

이 문서에서는 Microsoft Visual Basic 응용 프로그램에서 Microsoft Office Word를 자동화하여 우편물 레이블에 대한 편지 병합을 만들고 실행하는 방법을 설명합니다.

추가 정보

이 문서의 샘플 코드는 데이터 원본에 대해 탭으로 구분된 텍스트 파일을 사용합니다. 텍스트 파일에는 다음과 같은 필드가 있습니다.

  • Contact_Name
  • 주소
  • 구/군/시
  • Postal_Code
  • 국가

텍스트 편집기를 사용하여 텍스트 파일 데이터 원본을 만들 수 있습니다. 예를 들어 메모장을 사용할 수 있습니다.

데이터 원본을 만들 때는 탭 문자를 사용하여 필드(열)를 구분하고 캐리지 리턴을 사용하여 레코드(행)를 구분해야 합니다. 다음은 텍스트 파일이 표시되는 방식의 예입니다.

Contact_NameAddress City Postal_Code Country
Maria AndersObere Str. 57 Berlin 12209 Germany 
Thomas Hardy120 Hanover Sq. London WA1 1DP UK
Hanna MoosForsterstr. 57 Mannheim 68306 Germany
Laurence Lebihan 12, rue des Bouchers Marseille 13008 France

참고

탭으로 구분된 텍스트 파일 대신 다른 데이터 원본을 사용할 수 있습니다. 예를 들어 Microsoft Access 데이터베이스를 사용할 수 있습니다.

단계별 예제

  1. Visual Basic에서 새 표준 EXE 프로젝트를 시작합니다. 기본적으로 Form1이라는 양식이 만들어집니다.
  2. Form1에 CommandButton을 추가합니다.
  3. 자동화하려는 Word 버전의 Microsoft Word 개체 라이브러리를 선택한 다음 확인을 클릭합니다.
  4. 다음 코드를 Form1의 코드 창에 복사합니다.
    Private Sub Command1_Click()
    
    Dim oApp As Word.Application
        Dim oDoc As Word.Document
    
    'Start a new document in Word
        Set oApp = CreateObject("Word.Application")
        Set oDoc = oApp.Documents.Add
    
    With oDoc.MailMerge
    
    'Insert the mail merge fields temporarily so that
            'you can use the range that contains the merge fields as a layout
            'for your labels -- to use this as a layout, you can add it
            'as an AutoText entry.
            With .Fields
                .Add oApp.Selection.Range, "Contact_Name"
                oApp.Selection.TypeParagraph
                .Add oApp.Selection.Range, "Address"
                oApp.Selection.TypeParagraph
                .Add oApp.Selection.Range, "City"
                oApp.Selection.TypeText "  "
                .Add oApp.Selection.Range, "Postal_Code"
                oApp.Selection.TypeText " -- "
                .Add oApp.Selection.Range, "Country"
            End With
            Dim oAutoText As Word.AutoTextEntry
            Set oAutoText = oApp.NormalTemplate.AutoTextEntries.Add("MyLabelLayout", oDoc.Content)
            oDoc.Content.Delete 'Merge fields in document no longer needed now
                                'that the AutoText entry for the label layout
                                'has been added so delete it.
    
    'Set up the mail merge type as mailing labels and use
            'a tab-delimited text file as the data source.
            .MainDocumentType = wdMailingLabels 
            .OpenDataSource Name:="C:\data.txt" 'Specify the data source here
    
    'Create the new document for the labels using the AutoText entry
            'you added -- 5160 is the label number to use for this sample.
            'You can specify the label number you want to use for the output
            'in the Name argument.
            oApp.MailingLabel.CreateNewDocument Name:="5160", Address:="", _
                AutoText:="MyLabelLayout", LaserTray:=wdPrinterManualFeed
    
    'Execute the mail merge to generate the labels.
            .Destination = wdSendToNewDocument
            .Execute
    
    'Delete the AutoText entry you added
            oAutoText.Delete
    
    End With
    
    'Close the original document and make Word visible so that
    
    'the mail merge results are displayed
        oDoc.Close False
        oApp.Visible = True
    
    'Prevent save to Normal template when user exits Word
        oApp.NormalTemplate.Saved = True
    
    End Sub
    
    
    이 코드의 OpenDataSource 메서드에 대한 Name 인수는 데이터 원본을 c:\data.txt 참조합니다. 데이터 원본에 다른 경로 또는 다른 파일 이름이 있는 경우 코드에서 이 줄을 적절하게 수정합니다.
  5. F5 키를 눌러 프로그램을 실행한 다음 Command1을 클릭합니다. 메일 레이블 문서는 데이터 원본에서 가져온 데이터를 사용하여 만들어집니다.

참조

Word를 자동화하는 방법 또는 편지 병합 문서를 만드는 방법에 대한 자세한 내용은 다음 문서 번호를 클릭하여 Microsoft 기술 자료에서 문서를 확인합니다.

220911 Visual C++ 및 MFC를 사용하여 Microsoft Word를 자동화하여 편지 병합을 수행하는 방법

212034 Word에서 편지 병합을 사용하여 우편물 레이블을 만드는 방법