Using Sort in VBA for a Range that Changes

本小妞迷上赌 提交于 2019-12-22 12:18:26

问题


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:


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


来源:https://stackoverflow.com/questions/22174908/using-sort-in-vba-for-a-range-that-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!