mek zek
mek zek

Reputation: 117

Create table in Word Document From Access using VBA

I am trying to create tables in a Word document template from my Access database.

This bit of code runs fine from Word itself and creates tables as required. I was wondering if its possible to run this code from Access and point to a specific word document in which to create the tables.

Dim numberOfTables As Integer
Dim iCount As Integer

numberOfTables = InputBox("How many tables to make?", "Tables")

For iCount = 0 To numberOfTables - 1

    ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=2, NumColumns:= _
        3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
    With Selection.Tables(1)
        If .Style <> "Table Grid" Then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        '.ApplyStyleRowBands = True 'Office 2010
        '.ApplyStyleColumnBands = False 'Office 2007
    End With

    Selection.EndKey Unit:=wdStory
    Selection.TypeParagraph

Next iCount

Upvotes: 2

Views: 4553

Answers (1)

ib11
ib11

Reputation: 2568

What you need to do is to first open a new instance of Word from Access. This is done by the following command:

Set wrdApp = CreateObject("Word.Application")

Then to make it visible and to add a document, you use this object from that point on:

wrdApp.Visible = True
Set myDoc = wrdApp.Documents.Add   'Here you should also keep the new document as an object so you can directly refer to it

Or if you use a template you need to open it instead:

wrdApp.Visible = True
Set myDoc = wrdApp.Documents.Open ("C:\database\template.docx")

And then comes your code that you need to modify accordingly to the above:

For iCount = 0 To numberOfTables - 1

    myDoc.Tables.Add Range:=Selection.Range, NumRows:=2, NumColumns:= _
        3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
    With myDoc.ActiveWindow.Selection.Tables(1)  
'Note here that for the Selection object you need to refer to the active window
        If .Style <> "Table Grid" Then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        '.ApplyStyleRowBands = True 'Office 2010
        '.ApplyStyleColumnBands = False 'Office 2007
    End With

    myDoc.ActiveWindow.Selection.EndKey Unit:=wdStory
    myDoc.ActiveWindow.Selection.TypeParagraph

Next iCount

This should get you started.

Upvotes: 3

Related Questions