Function to refer to each table in a document and count their rows

J

JuanManuel

I’m working on a small project to incorporate some vba functionality to a
template in Microsoft Word. It is a fairly long template (over 30 pages) with
extensive use of tables. We would like to be able to collapse and expand rows
as needed, so that the printed document only shows what is really relevant.

I have found VBA code that seems to be useful in achieving this collapsing
and expanding of rows or lines of text, except that I’ll need a function or
set of functions that would enable me to refer to each table in the document
and count the number of rows in each of them. I also need a way to refer to
each and ever paragraph in the template and count the number of lines in
each. How can I do this?

Thank you
 
S

StevenM

To: Juan,

Note that a "paragraph" includes every cell of a table, plus the mark right
of each row of a table. So a document with only one table (with five columns
and two rows) will have 13 paragraphs! One paragraph for each cell, one
additional paragraph for each row, and one paragraph at the end of the table.

Counting lines is more difficult.

Sub CountTablesRowsParas()
Dim oDoc As Document
Dim oRange As Range
Dim nTables As Long
Dim nRows As Long
Dim nParas As Long
Dim nIndex As Long

Set oDoc = ActiveDocument
Set oRange = oDoc.Range
nTables = oRange.Tables.Count
MsgBox "This document has " & nTables & " table(s)."
If nTables > 0 Then
nRows = oRange.Tables(1).Rows.Count
MsgBox "The first table has " & nRows & " row(s)."
End If
nParas = oRange.Paragraphs.Count
MsgBox "This document has " & nParas & " paragraph(s)."
End Sub

Steven Craig Miller
 
S

StevenM

To: Juan,

The "test" needs a document with at least 4 paragraphs.

Sub TestCountNumberOfLines()
Dim nParas As Long
Dim nIndex As Long
Dim oRange As Range
Dim paraRange As Range

Set oRange = ActiveDocument.Range
nParas = oRange.Paragraphs.Count
If nParas > 3 Then
For nIndex = 1 To 3
Set paraRange = oRange.Paragraphs(nIndex).Range
MsgBox "Paragraph " & nIndex _
& " has " & CountNumberOfLines(paraRange) & " line(s)."
Next nIndex
End If
End Sub


Function CountNumberOfLines(ByVal oRange As Range) As Long
Dim nEnd As Long
Dim nLnEnd As Long
Dim nCount As Long

nCount = 1
nEnd = oRange.End
oRange.Collapse wdCollapseStart
oRange.Select
Set oRange = oRange.Parent.Bookmarks("\line").Range
oRange.Move wdCharacter, 1
nLnEnd = oRange.End
While (nLnEnd < nEnd)
nCount = nCount + 1
oRange.Collapse wdCollapseEnd
oRange.Select
Set oRange = oRange.Parent.Bookmarks("\line").Range
oRange.Move wdCharacter, 1
nLnEnd = oRange.End
Wend
CountNumberOfLines = nCount
End Function

Steven Craig Miller
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top