我在VBA中有一系列单元格,每次运行代码时都会更改。我正在尝试编写代码,以便按照F列对此范围进行排序。
我的问题是,它只能是这个特定范围的细胞。在这个范围下面还有一些我不想排序的单元格,并且这个范围会改变大小。代码的一部分如下。到目前为止,我一直在无缘无故地尝试着这样做。
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这不管用。
我不能直接引用单元格(例如,我不能使用范围(“F2:F5”)),因为每次运行代码时,这些单元格都位于不同的位置。我知道如何找到我需要排序的内容,甚至选择它,但是我很难告诉排序函数要按哪一列排序。
有人能帮我吗?提前谢谢你!
发布于 2014-03-04 16:45:09
如果我理解得对,这会有帮助的。它找出所选区域的行号,然后用这些数字在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 Subhttps://stackoverflow.com/questions/22174908
复制相似问题