לקבלת גירסת .NET של Microsoft Visual C# של מאמר זה, ראה 316384.  

לקבלת גירסת Microsoft Visual Basic 6.0 של מאמר זה, ראה 313193.  

סיכום

מאמר שלב אחר שלב זה מתאר כיצד ליצור מסמך חדש ב- Word באמצעות אוטומציה מ- Visual Basic .NET.

קוד לדוגמה

הקוד לדוגמה במאמר זה מדגים כיצד לבצע את הפעולות הבאות:

  • הוסף פיסקאות עם טקסט ועיצוב.

  • עיין בטווחים שונים במסמך ושנה אותם.

  • הוסף טבלאות, עצב טבלאות ואכלס את הטבלאות בנתונים.

  • הוסף תרשים.

כדי ליצור מסמך Word חדש באמצעות אוטומציה מ- Visual Basic .NET, בצע את הפעולות הבאות:

  1. הפעל את Microsoft Visual Studio .NET. בתפריט קובץ, לחץ על חדש ולאחר מכן לחץ על Project. תחת סוגי פרוייקטים, לחץ על פרוייקטים של Visual Basic ולאחר מכן לחץ על יישום Windows תחת תבניות. Form1 נוצר כברירת מחדל.

  2. הוסף הפניה לספריית האובייקטים של Microsoft Word. לשם כך, בצע את השלבים הבאים:

    1. בתפריט פרוייקט, לחץ על הוסף הפניה.

    2. בכרטיסיה COM, אתר את ספריית האובייקטים של Microsoft Word ולחץ על בחר.הערה Microsoft Office 2003 וגירסאות מאוחרות יותר של Office כוללות הרכבות Interop ראשיות (PIAs). Microsoft Office XP אינו כולל PIAs, אך ניתן להוריד אותם.  

    3. לחץ על אישור בתיבת הדו-שיח הוספת הפניות כדי לקבל את הבחירות שלך. אם אתה מקבל בקשה ליצירת עטופים עבור הספריות שבחרת, לחץ על כן.

  3. בתפריט תצוגה, בחר ארגז כלים כדי להציג את ארגז הכלים ולאחר מכן הוסף לחצן לטופס1.

  4. לחץ פעמיים על לחצן1. חלון הקוד עבור הטופס מופיע.

  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 כדי לבנות ולהפעיל את התוכנית.

לאחר השלמת הקוד, בדוק את המסמך שנוצר עבורך. המסמך מכיל שני עמודים של פיסקאות מעוצבות, טבלאות ותרשים.

שימוש בתבנית

אם אתה משתמש באוטומציה כדי לבנות מסמכים בתבנית משותפת, תוכל ליהנות מהפעלת התהליך במסמך חדש המבוסס על תבנית מעוצבת מראש. השימוש בתבנית עם לקוח האוטומציה של Word כולל שני יתרונות משמעותיים על-ידי בניית מסמך מכלום:

  • באפשרותך לקבל שליטה גדולה יותר על העיצוב והמיקום של אובייקטים לאורך כל המסמכים שלך.

  • באפשרותך לבנות את המסמכים שלך עם פחות קוד.

באמצעות תבנית, באפשרותך לכוונן את מיקום הטבלאות, הפיסקאות והאובייקטים האחרים במסמך, וכן לכלול עיצוב באובייקטים אלה. באמצעות אוטומציה, באפשרותך ליצור מסמך חדש המבוסס על התבנית שלך עם קוד כגון:

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

בתבנית שלך, באפשרותך להגדיר סימניות כך שללקוח האוטומציה שלך יהיה אפשרות למלא טקסט משתנה במיקום ספציפי במסמך, באופן הבא:

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 Knowledge Base:

301656 כיצד להפוך את Word לאוטומטי כדי לבצע מיזוג דואר מ- Visual Basic .NET

זקוק לעזרה נוספת?

מעוניין באפשרויות נוספות?

גלה את יתרונות המנוי, עיין בקורסי הדרכה, למד כיצד לאבטח את המכשיר שלך ועוד.