Philip said:
I am working with a document in Word X for mac. Is there a way to
sort a list of words by word length?
Hi, Philip,
This macro should word equally well in Word for Mac or Windows:
Sub SortByWordLength()
Dim nRow As Long
Dim bPlainText As Boolean
If Not Selection.Information(wdWithInTable) Then
' if the selected text is already in a table,
' skip the next part, otherwise we need to
' make it a table so we can add a temporary
' column for the lengths
bPlainText = True
' ConvertToTable can't work on an
' insertion point, so select everything
If Selection.Type = wdSelectionIP Then
Selection.WholeStory
End If
' make the table
Selection.ConvertToTable numcolumns:=1
End If
With Selection.Tables(1)
' add the temporary column as new col. 1
.Columns.Add beforecolumn:=.Columns(1)
' in each row, fill the first cell with the
' length of the (first or only) word in the
' second cell (formerly the first column)
For nRow = 1 To .Rows.Count
.Cell(nRow, 1).Range.Text = _
Len(.Cell(nRow, 2).Range.Words(1))
Next nRow
' sort on the first column (lengths)
.Sort
' the lengths are no longer needed, so
' get rid of them
.Columns(1).Delete
' if we started with plain text,
' convert back to text
If bPlainText Then
.ConvertToText
End If
End With
End Sub
If the starting selection is in a table that has any vertically merged
cells, the macro fails badly -- you get an error message saying that "Word
found no valid records to sort" and leaves the table with its extra column.
If the table contains horizontally merged cells, the macro fails but hasn't
yet made any changes in the document. These aren't problems if you never run
the macro in a document that contains a table with merged cells; otherwise
it needs some special error-trapping.