Friday, July 10, 2009

Excel VBA: How to Create a Word Table

Sub CreateWordTable()
Dim oWORD As Word.Application
Dim oDOC As Word.Document
Dim oTable As Word.Table

Dim oWS As Worksheet
Dim lMaxRow As Long
Dim lRow As Long
Dim lMaxCol As Long
Dim lCol As Long

Set oWS = Worksheets(1)
lMaxRow = oWS.Cells.SpecialCells(xlCellTypeLastCell).Row
lMaxCol = oWS.Cells.SpecialCells(xlCellTypeLastCell).Column

Set oWORD = New Word.Application
oWORD.Visible = True
Set oDOC = oWORD.Documents.Add
Set oTable = oDOC.Tables.Add(oWORD.Selection.Range, lMaxRow, lMaxCol)
For lRow = 1 To lMaxRow Step 1
For lCol = 1 To lMaxCol Step 1
oTable.Rows(lRow).Cells(lCol).Range.Text = oWS.Cells(lRow, lCol)
Next lCol
Next lRow

Set oTable = Nothing
oDOC.Save
oDOC.Close
Set oDOC = Nothing
oWORD.Application.Quit
Set oWORD = Nothing
End Sub

No comments:

Post a Comment