MS word and VBA

Signo.X

Well-known member
Joined
Aug 21, 2006
Messages
76
Location
Australia
Programming Experience
1-3
Hello all,

how to read data from a MS word table and how to check if any specific data is null or empty ?

thanks,

signo.x
 
Signo-

ActiveDocuments.Tables is a 1-based collection of the tables in the document. You can walk through them as needed.

Each table has a Rows collection, and each row a Cells collection. So you can walk through the entire table with code like this:

VB.NET:
Sub readtable()

Dim myTable As Table
Dim myRow As Row
Dim myCell As Cell
Dim cellText As String

Set myTable = ActiveDocument.Tables(1)

For Each myRow In myTable.Rows
  For Each myCell In myRow.Cells
    cellText = myCell.Range.Text
    ' This line removes the trailing end of cell marker
    cellText = Trim$(Left$(cellText, Len(cellText) - 2))
    If Len(cellText) = 0 Then
      'Cell is empty; do something
    End If
  Next myCell
Next myRow

End Sub


Note that every cell's Range.Text property is terminated with a Chr$(13) & Chr$(7) (end of cell marker). You can see where I remove them and Trim$() the line. Then if the length of the text is zero, it's empty. Or you could trim it an just see if it equals Chr$(13) & Chr$(7). Your choice

Note also that if you set the cell text, you don't need to add back the Chr$(13) & Chr$(7). Apparently Word does that for you. But you do need to account for it when you read cell text.

Hope this helps!
 
Thanks heaps infidel,

another Questions,.
1. how do you specify the location of the word document on you local hard drive "C:\temp\word.doc"? what class or object is needed?
2. you refered to ActiveDocument , how will it know which document is active?
3. i have table with 5 rows, using ur example, is there any way where i can skip the first and the 3rd row ? OR how can i refer to a specific row or cell in a row ?


~ signo.x
 
Last edited:
1. Do you mean to open a file or save it?

To open:
Documents.Add("c:\path\to\file.doc")

To save to the same place
ActiveDocument.Save

To save somewhere else:
ActiveDocument.SaveAs("c:\new\path\to\file.doc")

2. ActiveDocument is the document of all open Word docs that has (or last had) the focus. Word knows. If you want a specific file you can use

Documents("file.doc").Activate

first. Then ActiveDocument will be file.doc.

3. You should be able to do something like:

Set myRow = Tables([tablenumber]).Rows([rownumber])

and then go from there.

Or

myText = ActiveDocument.Tables(1).Rows(1).Cells(2).Range.Text

you get the idea.
 
Back
Top