Identificativo articolo: 301656 - Ultima modifica: mercoledì 31 gennaio 2007 - Revisione: 8.0

Automazione di Microsoft Word per l'esecuzione della stampa unione da Visual Basic .NET

Suggerimento di sistemaIl presente articolo fa riferimento a un sistema operativo diverso da quello in uso. Il contenuto dell'articolo che potrebbe non essere relativo al sistema in uso è disabilitato.
Questo articolo è stato precedentemente pubblicato con il codice di riferimento I301656

In questa pagina

Espandi tutto | Chiudi tutto

Sommario

In questo articolo viene descritto come utilizzare Microsoft Word per creare un documento di stampa unione mediante la funzionalità di automazione da Visual Basic .NET.

Informazioni

L'automazione è un processo che consente ad applicazioni scritte in linguaggi come Visual Basic .NET di controllare altre applicazioni a livello di programmazione. L'automazione in Microsoft Word consente di eseguire operazioni quali la creazione di nuovi documenti, l'aggiunta di testo ai documenti e la formattazione di documenti. In Microsoft Word e in altre applicazioni di Microsoft Office l'automazione consente di eseguire a livello di programmazione praticamente tutte le azioni che è possibile eseguire manualmente tramite l'interfaccia utente.

In Word questa funzionalità a livello di programmazione viene esposta tramite un modello a oggetti. Il modello a oggetti è un insieme di classi e metodi utilizzati come controparti dei componenti logici di Word. Esistono, ad esempio, oggetti Application, Document e Paragraph contenenti le funzionalità degli oggetti corrispondenti in Word. Per accedere al modello a oggetti da Visual Basic .NET, è possibile impostare un riferimento del progetto alla libreria dei tipi.

In questo articolo viene illustrato come impostare il riferimento del progetto corretto alla libreria dei tipi di Word per Visual Basic .NET e viene fornito il codice di esempio per l'automazione di Word.

Creazione di un client di automazione per Word

  1. Avviare Microsoft Visual Studio .NET.
  2. Scegliere Nuovo dal menu File, quindi Progetto. Selezionare Applicazione Windows dai tipi di progetto di Visual Basic. Per impostazione predefinita, viene creato il progetto Form1.
  3. Aggiungere un riferimento a Libreria oggetti di Microsoft Word. Per effettuare questa operazione, attenersi alla seguente procedura:
    1. Scegliere Aggiungi riferimento dal menu Progetto.
    2. Nella scheda COM individuare Libreria oggetti di Microsoft Word e fare clic su Seleziona.

      Nota In Microsoft Office 2003 sono inclusi gli assembly di interoperabilità primari (PIA, Primary Interop Assembly). Non sono invece inclusi in Microsoft Office XP, ma possono essere scaricati. Per ulteriori informazioni sugli assembly di interoperabilità primari di Office XP, fare clic sul numero dell'articolo della Microsoft Knowledge Base riportato di seguito:
      328912  (http://support.microsoft.com/kb/328912/ ) INFO: Assembly di interoperabilità primari (PIA) di Microsoft Office XP disponibili per il download
    3. Scegliere OK nella finestra di dialogo Aggiungi riferimento per accettare le selezioni effettuate.
  4. Scegliere Casella degli strumenti dal menu Visualizza per visualizzare la casella degli strumenti, quindi aggiungere un pulsante a Form1.
  5. Fare doppio clic su Button1. Viene visualizzata la finestra del codice del form.
  6. Nella finestra del codice sostituire il codice riportato di seguito
        Private Sub Button1_Click(ByVal sender As System.Object, _
           ByVal e As System.EventArgs) Handles Button1.Click
        End Sub
    					
    con:
        Dim wrdApp As Word.Application
        Dim wrdDoc As Word._Document
    
        Private Sub InsertLines(ByVal LineNum As Integer)
            Dim iCount As Integer
    
            ' Insert "LineNum" blank lines.
            For iCount = 1 To LineNum
                wrdApp.Selection.TypeParagraph()
            Next iCount
        End Sub
    
        Private Sub FillRow(ByVal Doc As Word.Document, ByVal Row As Integer, _
        ByVal Text1 As String, ByVal Text2 As String, _
        ByVal Text3 As String, ByVal Text4 As String)
    
            With Doc.Tables.Item(1)
                ' Insert the data in the specific cell.
                .Cell(Row, 1).Range.InsertAfter(Text1)
                .Cell(Row, 2).Range.InsertAfter(Text2)
                .Cell(Row, 3).Range.InsertAfter(Text3)
                .Cell(Row, 4).Range.InsertAfter(Text4)
            End With
        End Sub
    
        Private Sub CreateMailMergeDataFile()
            Dim wrdDataDoc As Word._Document
            Dim iCount As Integer
    
            ' Create a data source at C:\DataDoc.doc containing the field data.
            wrdDoc.MailMerge.CreateDataSource(Name:="C:\DataDoc.doc", _
                  HeaderRecord:="FirstName, LastName, Address, CityStateZip")
            ' Open the file to insert data.
            wrdDataDoc = wrdApp.Documents.Open("C:\DataDoc.doc")
            For iCount = 1 To 2
                wrdDataDoc.Tables.Item(1).Rows.Add()
            Next iCount
            ' Fill in the data.
            FillRow(wrdDataDoc, 2, "Steve", "DeBroux", _
                  "4567 Main Street", "Buffalo, NY  98052")
            FillRow(wrdDataDoc, 3, "Jan", "Miksovsky", _
                  "1234 5th Street", "Charlotte, NC  98765")
            FillRow(wrdDataDoc, 4, "Brian", "Valentine", _
                  "12348 78th Street  Apt. 214", "Lubbock, TX  25874")
            ' Save and close the file.
            wrdDataDoc.Save()
            wrdDataDoc.Close(False)
        End Sub
    
    
        Private Sub Button1_Click(ByVal sender As System.Object, _
           ByVal e As System.EventArgs) Handles Button1.Click
            Dim wrdSelection As Word.Selection
            Dim wrdMailMerge As Word.MailMerge
            Dim wrdMergeFields As Word.MailMergeFields
    
            Dim StrToAdd As String
    
            ' Create an instance of Word  and make it visible.
            wrdApp = CreateObject("Word.Application")
            wrdApp.Visible = True
    
            ' Add a new document.
    
            wrdDoc = wrdApp.Documents.Add()
            wrdDoc.Select()
    
            wrdSelection = wrdApp.Selection()
            wrdMailMerge = wrdDoc.MailMerge()
    
            ' Create MailMerge Data file.
            CreateMailMergeDataFile()
    
            ' Create a string and insert it in the document.
            StrToAdd = "State University" & vbCr & _
                        "Electrical Engineering Department"
            wrdSelection.ParagraphFormat.Alignment = _
                        Word.WdParagraphAlignment.wdAlignParagraphCenter
            wrdSelection.TypeText(StrToAdd)
    
            InsertLines(4)
    
            ' Insert merge data.
            wrdSelection.ParagraphFormat.Alignment = _
                        Word.WdParagraphAlignment.wdAlignParagraphLeft
            wrdMergeFields = wrdMailMerge.Fields()
            wrdMergeFields.Add(wrdSelection.Range, "FirstName")
            wrdSelection.TypeText(" ")
            wrdMergeFields.Add(wrdSelection.Range, "LastName")
            wrdSelection.TypeParagraph()
    
            wrdMergeFields.Add(wrdSelection.Range, "Address")
            wrdSelection.TypeParagraph()
            wrdMergeFields.Add(wrdSelection.Range, "CityStateZip")
    
            InsertLines(2)
    
            ' Right justify the line and insert a date field
            ' with the current date.
            wrdSelection.ParagraphFormat.Alignment = _
                   Word.WdParagraphAlignment.wdAlignParagraphRight
            wrdSelection.InsertDateTime( _
                  DateTimeFormat:="dddd, MMMM dd, yyyy", _
                  InsertAsField:=False)
    
            InsertLines(2)
    
            ' Justify the rest of the document.
            wrdSelection.ParagraphFormat.Alignment = _
                   Word.WdParagraphAlignment.wdAlignParagraphJustify
    
            wrdSelection.TypeText("Dear ")
            wrdMergeFields.Add(wrdSelection.Range, "FirstName")
            wrdSelection.TypeText(",")
            InsertLines(2)
    
            ' Create a string and insert it into the document.
            StrToAdd = "Thank you for your recent request for next " & _
                "semester's class schedule for the Electrical " & _
                "Engineering Department. Enclosed with this " & _
                "letter is a booklet containing all the classes " & _
                "offered next semester at State University.  " & _
                "Several new classes will be offered in the " & _
                "Electrical Engineering Department next semester.  " & _
                "These classes are listed below."
            wrdSelection.TypeText(StrToAdd)
    
            InsertLines(2)
    
            ' Insert a new table with 9 rows and 4 columns.
            wrdDoc.Tables.Add(wrdSelection.Range, NumRows:=9, _
                 NumColumns:=4)
    
            With wrdDoc.Tables.Item(1)
                ' Set the column widths.
                .Columns.Item(1).SetWidth(51, Word.WdRulerStyle.wdAdjustNone)
                .Columns.Item(2).SetWidth(170, Word.WdRulerStyle.wdAdjustNone)
                .Columns.Item(3).SetWidth(100, Word.WdRulerStyle.wdAdjustNone)
                .Columns.Item(4).SetWidth(111, Word.WdRulerStyle.wdAdjustNone)
                ' Set the shading on the first row to light gray.
                .Rows.Item(1).Cells.Shading.BackgroundPatternColorIndex = _
                 Word.WdColorIndex.wdGray25
                ' Bold the first row.
                .Rows.Item(1).Range.Bold = True
                ' Center the text in Cell (1,1).
                .Cell(1, 1).Range.Paragraphs.Alignment = _
                          Word.WdParagraphAlignment.wdAlignParagraphCenter
    
                ' Fill each row of the table with data.
                FillRow(wrdDoc, 1, "Class Number", "Class Name", "Class Time", _
                   "Instructor")
                FillRow(wrdDoc, 2, "EE220", "Introduction to Electronics II", _
                          "1:00-2:00 M,W,F", "Dr. Jensen")
                FillRow(wrdDoc, 3, "EE230", "Electromagnetic Field Theory I", _
                          "10:00-11:30 T,T", "Dr. Crump")
                FillRow(wrdDoc, 4, "EE300", "Feedback Control Systems", _
                          "9:00-10:00 M,W,F", "Dr. Murdy")
                FillRow(wrdDoc, 5, "EE325", "Advanced Digital Design", _
                          "9:00-10:30 T,T", "Dr. Alley")
                FillRow(wrdDoc, 6, "EE350", "Advanced Communication Systems", _
                          "9:00-10:30 T,T", "Dr. Taylor")
                FillRow(wrdDoc, 7, "EE400", "Advanced Microwave Theory", _
                          "1:00-2:30 T,T", "Dr. Lee")
                FillRow(wrdDoc, 8, "EE450", "Plasma Theory", _
                          "1:00-2:00 M,W,F", "Dr. Davis")
                FillRow(wrdDoc, 9, "EE500", "Principles of VLSI Design", _
                          "3:00-4:00 M,W,F", "Dr. Ellison")
            End With
    
            ' Go to the end of the document.
            wrdApp.Selection.GoTo(Word.WdGoToItem.wdGoToLine, _
                       Word.WdGoToDirection.wdGoToLast)
    
            InsertLines(2)
    
            ' Create a string and insert it into the document.
            StrToAdd = "For additional information regarding the " & _
                       "Department of Electrical Engineering, " & _
                       "you can visit our Web site at "
            wrdSelection.TypeText(StrToAdd)
            ' Insert a hyperlink to the Web page.
            wrdSelection.Hyperlinks.Add(Anchor:=wrdSelection.Range, _
               Address:="http://www.ee.stateu.tld")
            ' Create a string and insert it in the document.
            StrToAdd = ".  Thank you for your interest in the classes " & _
                       "offered in the Department of Electrical " & _
                       "Engineering.  If you have any other questions, " & _
                       "please feel free to give us a call at " & _
                       "555-1212." & vbCr & vbCr & _
                       "Sincerely," & vbCr & vbCr & _
                       "Kathryn M. Hinsch" & vbCr & _
                       "Department of Electrical Engineering" & vbCr
            wrdSelection.TypeText(StrToAdd)
    
            ' Perform mail merge.
            wrdMailMerge.Destination = _
                       Word.WdMailMergeDestination.wdSendToNewDocument
            wrdMailMerge.Execute(False)
    
            ' Close the original form document.
            wrdDoc.Saved = True
            wrdDoc.Close(False)
    
            ' Release References.
            wrdSelection = Nothing
            wrdMailMerge = Nothing
            wrdMergeFields = Nothing
            wrdDoc = Nothing
            wrdApp = Nothing
    
            ' Clean up temp file.
            System.IO.File.Delete("C:\DataDoc.doc")
        End Sub
    
    					
  7. Aggiungere quanto segue all'inizio di Form1.vb:
    Imports Microsoft.Office.Interop
    					
  8. Premere F5 per compilare ed eseguire il programma.
  9. Fare clic su Button1 per avviare l'automazione di Word ed eseguire la stampa unione.

Riferimenti

Per ulteriori informazioni, visitare il seguente sito Web Microsoft Developer Network (MSDN) (informazioni in lingua inglese):
Microsoft Office Development with Visual Studio
http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx (http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx)
Per ulteriori informazioni sull'automazione di Word con Microsoft Visual Basic 5.0 o 6.0, fare clic sui numeri degli articoli della Knowledge Base riportati di seguito:
285332  (http://support.microsoft.com/kb/285332/ ) Automazione di Word 2002 con Visual Basic per creare un'operazione di stampa unione
220607  (http://support.microsoft.com/kb/220607/ ) Automazione di Microsoft Word per eseguire la stampa unione da Visual Basic

Le informazioni in questo articolo si applicano a
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
  • Microsoft Office Word 2003
  • Microsoft Word 2002 Standard Edition
Chiavi: 
kbpia kbautomation kbhowto KB301656
LE INFORMAZIONI CONTENUTE NELLA MICROSOFT KNOWLEDGE BASE SONO FORNITE SENZA GARANZIA DI ALCUN TIPO, IMPLICITA OD ESPLICITA, COMPRESA QUELLA RIGUARDO ALLA COMMERCIALIZZAZIONE E/O COMPATIBILITA' IN IMPIEGHI PARTICOLARI. L'UTENTE SI ASSUME L'INTERA RESPONSABILITA' PER L'UTILIZZO DI QUESTE INFORMAZIONI. IN NESSUN CASO MICROSOFT CORPORATION E I SUOI FORNITORI SI RENDONO RESPONSABILI PER DANNI DIRETTI, INDIRETTI O ACCIDENTALI CHE POSSANO PROVOCARE PERDITA DI DENARO O DI DATI, ANCHE SE MICROSOFT O I SUOI FORNITORI FOSSERO STATI AVVISATI. IL DOCUMENTO PUO' ESSERE COPIATO E DISTRIBUITO ALLE SEGUENTI CONDIZIONI: 1) IL TESTO DEVE ESSERE COPIATO INTEGRALMENTE E TUTTE LE PAGINE DEVONO ESSERE INCLUSE. 2) I PROGRAMMI SE PRESENTI, DEVONO ESSERE COPIATI SENZA MODIFICHE, 3) IL DOCUMENTO DEVE ESSERE DISTRIBUITO INTERAMENTE IN OGNI SUA PARTE. 4) IL DOCUMENTO NON PUO' ESSERE DISTRIBUITO A SCOPO DI LUCRO.