Option Explicit
'Add a reference to MS Word xx.0 Object Library
Public Function AddTable(ByVal iRows As Integer, ByVal iCols As Integer) As Boolean
Dim oApp As Word.Application
Dim oDoc As Word.Document
Dim oTable As Word.Table
Dim oRowHeader As Word.Row
Dim x As Integer
Set oApp = New Word.Application
'Open either a blank new document or...
Set oDoc = oApp.Documents.Add
'open an exisiting document
'Set oDoc = oApp.Documents.Open("C:\Document1.doc")
oDoc.Activate
'Move to the end of the document
oApp.Selection.Move Unit:=wdStory
oApp.Selection.TypeParagraph
oApp.Selection.TypeParagraph
'Add a new table
Set oTable = oDoc.Tables.Add(Range:=Selection.Range, NumRows:=iRows, NumColumns:=iCols, _
DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitWindow)
'Format the table and populate
With oTable
If .Style <> "Table Grid" Then
.Style = "Table Grid"
End If
.ApplyStyleHeadingRows = True
.ApplyStyleLastRow = True
.ApplyStyleFirstColumn = True
.ApplyStyleLastColumn = True
'Populate and format the table header
Set oRowHeader = oTable.Rows.Item(1)
oRowHeader.Shading.Texture = wdTextureNone
oRowHeader.Shading.ForegroundPatternColor = wdColorAutomatic
oRowHeader.Shading.BackgroundPatternColor = wdColorGray25
For x = 1 To iCols
'Bold on for the cell
.Cell(1, x).Range.Font.Bold = True
.Cell(1, x).Range.Text = "ColumnHeader" & x
Next
End With
'Clean up and leave document open
Set oRowHeader = Nothing
Set oTable = Nothing
Set oDoc = Nothing
Set oApp = Nothing
End Function