Selasa, 14 Februari 2012

Interopabilitas Ms-Excel VBA dengan Ms-Word

Tambahkan referensi untuk MsWord di VBE : Tools -- References... -- Microsoft Word Object Library.

Kemudian tulis perintah VBA di bawah ini :

Sub CreateNewWordDoc()
    Dim wrdApp As Word.Application
    Dim wrdDoc As Word.Document
    Dim wrdTable As Word.Table
    Dim xText, xText2
    Dim i As Integer
    Set wrdApp = CreateObject("Word.Application")
    Set wrdDoc = wrdApp.Documents.Add ' create a new document
    Set wrdRange = wrdDoc.Range
    wrdApp.Visible = True
    
    For i = 1 To 10
        xText = Worksheets("Sheet1").Cells(i, 1).Value
        xText2 = Worksheets("Sheet1").Cells(i, 2).Value
        
        Set wrdRange = wrdDoc.Range
        With wrdRange
            .Collapse Direction:=wdCollapseEnd
            .InsertParagraphAfter
            .Collapse Direction:=wdCollapseEnd
        End With
        
        'Create table
        Set wrdTable = wrdDoc.Tables.Add(Range:=wrdRange, NumRows:=1, NumColumns:=2)
        
        With wrdTable
            With .Cell(i, 1).Range
                .InsertAfter xText
            End With
            xText = Worksheets("Sheet1").[a2].Value
            With .Cell(i, 2).Range
                .InsertAfter xText2
            End With
        End With
    Next i

    Set wrdDoc = Nothing
    Set wrdApp = Nothing
End Sub

Tidak ada komentar: