简体   繁体   English

在VBA中使用Sort更改范围

[英]Using Sort in VBA for a Range that Changes

I have a range of cells in VBA that changes each time the code is run. 我在VBA中有一系列单元,每次运行代码时都会改变。 I am trying to write code so that this range is sorted by column F. 我正在尝试编写代码,以便将该范围按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. 我不能直接引用这些单元格(例如,我不能使用Range(“ F2:F5”)),因为每次运行代码时这些单元格都位于不同的位置。 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! 提前非常感谢您!

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. 它找出所选区域的行号,然后在F列中使用这些数字进行范围选择,并将其用作订购的键。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM