PDA

View Full Version : Sort text by paragraph in a Word table cell



Strongs
10-25-2007, 09:05 AM
Hi everyone,

I am trying to sort a single cell in a Word table. I have tried the following code, but with no success. I know this should be a very straight forward process, but seem to be having difficulty in getting it to work.

A fresh pair of eyes would be appreciated.


Dim srtCell as Range

Set srtCell = targetDoc.Tables(1).Cell(10, 2).Range
srtCell = Left(srtCell, Len(srtCell) - 2)
srtCell.Select
srtCell.SortDescending

Regards,

lucas
10-25-2007, 09:12 AM
Sorting cells is easy in Excel....

OTWarrior
10-25-2007, 09:21 AM
have you tried recording a macro when you sort a column?

Strongs
10-25-2007, 10:40 AM
Hi OTWarrior,

I have tried to record a macro to do this, but the amount of text in the cell will vary from document to document. Selecting the text manually and sorting the cell is straight forward. However, if one selects the complete cell (including end of cell marker) then Word throws an error when sort is invoked.

The trick is (I believe) to select only the text excluding the end of cell marker, which I am attempting to do with the posted code, but with no success.

Thanks for the suggestion though.

fionabolt
10-26-2007, 06:34 AM
Here's a solution that makes sure the range doesn't contain the cell end marker or the row end marker.

The sortascending/sortdescending method you were using is a simplified version of the sort method which give you more options.


Dim srtCell As Range
Dim sCell As String
Dim targetDoc As Document

Set targetDoc = ActiveDocument

Set srtCell = targetDoc.Tables(1).Cell(10, 2).Range
'convert the contents of the range to a string
'so you can investigate if it contains the end of the cell
sCell = srtCell
CheckforRowEndAgain:
'ASC(7) is the character for the end of the cell, or table row
If Asc(Right(sCell, 1)) = 7 Then
srtCell.SetRange srtCell.Start, srtCell.End - 1
sCell = srtCell
GoTo CheckforRowEndAgain
'just incase its a nested table or something
End If
srtCell.Sort Excludeheader:=True, sortorder:=wdSortOrderDescending

Strongs
10-26-2007, 09:29 AM
Hi fionabolt,

Thanks for the post. Superb! Just had to add srtCell.Select to make it work.
Makes sense when you know how.
Thanks a million.