Using Sort in VBA for a Range that Changes

2019-05-23 03:37发布

I have a range of cells in VBA that changes each time the code is run. I am trying to write code so that this range is sorted by column F.

The problem I am having is that it can only be this specific range of cells. There are other cells underneath this range that I do not want sorted, and this range changes in size. Part of the code is below. This is what I have tried so far with no luck.

Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select

vtools = Selection

ActiveWorkbook.Worksheets("Exceptions Weekly Summary").Sort.SortFields.Add Key _
    :=Range(vtools), SortOn:=xlSortOnValues, Order:=xlAscending, _
    DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Exceptions Weekly Summary").Sort
    .SetRange Range("B11:H14")
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

This does not work.

I cannot directly reference the cells (I cannot use Range("F2:F5") for example) because these cells are in different places each time the code is run. I know how to find what I need sorted, and even select it, but I am having trouble telling the sort function which column to sort by.

Can someone help me with this? Thank you so much in advance!

1条回答
Fickle 薄情
2楼-- · 2019-05-23 04:16

If I understood correctly this will help. It finds out the row numbers of the selected area and then makes a range in column F with these numbers and uses this as the key for ordering.

Sub sortOnlySelectedArea()

Dim actSheet As Worksheet
Dim upper, lower As Integer
Dim tempString As String
Dim selectedArea As Range

Set actSheet = Application.Worksheets("Sheet1")

' here you have to put in your part to make the right selection
actSheet.Range("E5:G6").Select
Set selectedArea = Selection

upper = selectedArea.Row
lower = upper + selectedArea.Rows.Count - 1

tempString = "F" & CStr(upper) & ":F" & CStr(lower)
actSheet.Sort.SortFields.Clear
actSheet.Sort.SortFields.Add Key:=Range(tempString), _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With actSheet.Sort
    .SetRange selectedArea
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

End Sub
查看更多
登录 后发表回答