PDA

View Full Version : [SOLVED:] Create table in Word Document From Access using VBA



imo92
05-12-2016, 07:12 AM
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

jonh
05-12-2016, 08:35 AM
You need to create a variable that points to a specific document, not just the active one, e.g. this would open a new file based on the normal template and create a 3 column table from table1 in Access.



Private Const WRD_TEMPLATE = "normal.dotm"


Private Sub Command0_Click()
'access stuff
Dim db As DAO.Database
Dim rs As DAO.Recordset

'word stuff
Dim w As Word.Application
Dim wd As Word.Document
Dim t As Word.Table
Dim rw As Word.Row

'get some data -3 fields
Set db = CurrentDb
Set rs = db.OpenRecordset("select fld1,fld2,fld3 from table1")

'open word file / template and make Word visible
Set w = CreateObject("Word.Application")
Set wd = w.Documents.Add(WRD_TEMPLATE, , , True)
w.Visible = True
w.Activate

'add a table
Set t = wd.Tables.Add(w.Selection.Range, 1, 3)

'do formatting
t.Borders.Enable = True
With t.Range.Font
.Name = "Arial"
.Size = 10
.Color = RGB(68, 5, 121)
End With

'add rows to table
Do Until rs.EOF
Set rw = t.Rows.Add()
rw.Cells(1).Range.Text = rs(0).Value
rw.Cells(2).Range.Text = rs(1).Value
rw.Cells(3).Range.Text = rs(2).Value

rs.MoveNext
Loop

rs.Close

End Sub

imo92
05-23-2016, 12:16 AM
Sorry for the late reply. Thanks that worked perfectly.

However if I wanted to create this table in a certain location how would I do it. I'm pointing to a document that requires the table between paragraph 2 and 3 for example. I tried playing around with the Range object but cant seem to get it to work.

jonh
05-23-2016, 02:52 AM
'insert table into a new 3rd paragraph
Set t = wd.Tables.Add(wd.Paragraphs.Add(wd.Paragraphs(3).Range).Range, 1, 3)