vbams-wordword-table

Reading text in a table with merged cells


I need to read from the table in incoming Word documents. These tables can be of two types:

enter image description here

The first row in both tables can be read without problems: I locate the first cell, expand the range or selection to the row and read contents of the cells, then move the selection down and so on.

But in the second case I need to read the text contained in the cells with "Min" and "Max" (because sometimes it is "Max | Min").

My questions are:

  1. how to recognize what type of table is there; and
  2. how can I read the contents of cells that contain "Min" and "Max in the picture?

Solution

  • "how to recognize what type of table is there" is really too general a question.

    For the specific example you show (with an arbitrary number of rows) then you could use something like the following to distinguish between the two:

    With ActiveDocument.Tables(1) ' or (2)
      If (.Rows.Count * .Columns.Count) = .Range.Cells.Count Then
        ' you have your first example
      Else
        ' you have your second example
      End If
    End With
    

    Or you could use something like this, because in this case you know that cell (2,4) and cells(6) must exist.

    With ActiveDocument.Tables(1) ' or (2)
      If .Cell(2,4).Range.Start = .Range.Cells(6).Start Then
        ' you have your second example
      Else
        ' you have your first example
      End If
    End With
    

    Once you have established that it is your second example, you could do something like

    Dim MinColumn As Long
    Dim MaxColumn As Long
    Dim theRow As Long
    With ActiveDocument.Tables(2)
      If UCase(Trim(.Cell(2,4).Range.Text)) = "MIN" then
        MinColumn = 4
      Else
        MinColumn = 5
      End If
      For theRow = 3 To .Rows.Count
        Debug.Print "Row " & CStr(theRow) & ", Min: " & .Cell(theRow,MinColumn).Range.Text  
      Next
    End With