Sort Selected Columns In Table

J

John

Hi there,

I'm trying to write a quick procedure to sort the selected columns in a
table. I've come up with the code below that ideally will enable the user
to select, say, two colums in a five column table and sort each one in turn
(leave the other columns unaffected).....:

Dim col As Word.Column

For Each col In Selection.Columns
col.Sort ExcludeHeader:=False, _
SortFieldType:=wdSortFieldAlphanumeric, _
SortOrder:=wdSortOrderAscending
Next col

......but this seems to sort adjacent selected columns as well. I've seen
that the Sort method for a Selection has a SortColumn flag, but this seems
to be a less flexible approach.

Can anyone tell me the best way to modify the above?

Many thanks

John
 
D

Dave Lett

Hi John,

I think you have to use the selection object rather than the column object.
The following works on my machine:

Dim oRng As Range
Dim iCol As Integer
Dim iStart As Integer
Dim iEnd As Integer
Dim oTbl As Table

''' set a reference to the current selection
Set oRng = Selection.Range

''' set a reference to the current table
Set oTbl = Selection.Tables(1)

With Selection
''' get the index number of the first selected column
iStart = .Information(wdStartOfRangeColumnNumber)
''' get the index number of the last selected column
iEnd = .Information(wdEndOfRangeColumnNumber)
End With

For iCol = iStart To iEnd
''' individually select each column in the original selection
oTbl.Columns(iCol).Select
''' sort each column individually
Selection.Sort SortFieldType:=wdSortFieldAlphanumeric,
SortOrder:=wdSortOrderAscending, _
SortColumn:=True
Next iCol

''' reselect the original selection
oRng.Select

HTH,
Dave
 
J

John

Perfect. Thanks very much Dave.

One other question that's related to this, is, is there a way for blank
cells to be either left out altogether or chucked to the bottom of the
sorted list? I suppose thinking about it that I could continue with a
delete (shift up) blank cells at the end for each column, but are you aware
of a flag that would do this automatically?

In any case, thanks again for your help.

Best regards

John
 

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