Word a Report Writer

  • Thread starter Thread starter Anatoly Kurilin
  • Start date Start date
A

Anatoly Kurilin

Hi, I got no problems with producing Word documents with fixed number of
bookmarks using Automation, but I've no idea how to add a variable number
of lines with bookmarks depending on the number of records in subordinate
tables.

Thanks in advance,
AK
 
Anatoly Kurilin said:
Hi, I got no problems with producing Word documents with fixed number of
bookmarks using Automation, but I've no idea how to add a variable number
of lines with bookmarks depending on the number of records in subordinate
tables.

Here's some code I use to create a table in Word using automation. The table
then adds however many rows that are in the Access ADO recordset. The
function CreateTableFromRecordset was adapted from some code in one of Ken
Getz's books:

If Not rs.BOF And Not rs.EOF Then
With CreateTableFromRecordset( _
objWord.ActiveDocument.Bookmarks("Details").Range, rs, True)

' Apply formatting
.AutoFormat wdTableFormatProfessional
.AutoFitBehavior wdAutoFitContent

.Range.ParagraphFormat.Alignment = wdAlignParagraphLeft
.Columns(5).Select
objWord.Selection.ParagraphFormat.Alignment =
wdAlignParagraphRight
.Columns(6).Select
objWord.Selection.ParagraphFormat.Alignment =
wdAlignParagraphRight
objWord.Selection.MoveDown
End With
End If

Function CreateTableFromRecordset( _
rngAny As Word.Range, _
rstAny As ADODB.Recordset, _
Optional fIncludeFieldNames As Boolean = False) _
As Word.Table

Dim objTable As Word.Table
Dim fldAny As ADODB.Field
Dim varData As Variant
Dim strBookmark As String
Dim cField As Long

' Get the data from the recordset
varData = rstAny.GetString()

' Create the table
With rngAny

' Creating the basic table is easy,
' just insert the tab-delimted text
' add convert it to a table
.InsertAfter varData
Set objTable = .ConvertToTable()

' Field names are more work since
' you must do them one at a time
If fIncludeFieldNames Then
With objTable

' Add a new row on top and make it a heading
.Rows.Add(.Rows(1)).HeadingFormat = True

' Iterate through the fields and add their
' names to the heading row
For Each fldAny In rstAny.Fields
cField = cField + 1
.Cell(1, cField).Range.Text = fldAny.Name
Next
End With
End If
End With
Set CreateTableFromRecordset = objTable
End Function
 
Back
Top