我正在寻找在A列的一个单元格中创建带有特定文本的动态行后对数据进行排序的方法。我能够设置条件,即仅在定位单元格后才对数据进行排序,但是我在尝试仅将排序应用于该位置以外的行时遇到了麻烦。这是我尝试过的,尝试仅对单元格8不等于单元格9以及单元格C以外的行以下的数据进行排序:
Dim intl As Range
Dim rSortRangez As Range
Dim iRowz As Integer, iColz As Integer
Dim cus As Range
Set intl = shtDest.Range("C8")
iRowz = intl.Row
iColz = intl.Column
Set rSortRangez = sheets("Sheet1").Range("A8", "P99")
Set cus = intl.Offset(1, 0)
Do
For Each intl In rSortRangez
If intl <> intl.Offset(1, 0) Then
rSortRangez.Sort _
Key1:=sheets("Sheet1").Range("cus"), Order1:=xlDescending, _
Header:=xlNo, OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, _
DataOption2:=xlSortNormal, DataOption3:=xlSortNormal
答案 0 :(得分:0)
您可以使用vba Range.Sort方法。
它可以如下使用:
Dim customSortRangeString As String
customSortRangeString = "C1:E5" 'enter in whatever you want
'key1 is the column that you will be sorting based on the first time.
'order1 is the order that it will sort the first time.
'header tells excel that the first row contains headers.
'Note: there are also key2 and key3 (as well as an order for each) allowing you to have multiple
'search criteria.
ActiveWorkbook.Worksheet("YOUR WORKSHEET HERE").Range(customSortRangeString).Sort key1:=Range("C2"), _
order1:=xlAccending, header:=xlYes
有关排序方法的更多信息,请参见here
更新-19/5/9 :根据此答案注释中提供的条件,为动态排序范围添加了信息。
Private Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim totalRow As Integer
Dim startSortRow As Integer
Dim sortRange As String
Dim sortKey As String
'Setting both the workbook and sheet to variables to make them easier to use.
Set wb = ActiveWorkbook
Set ws = wb.Worksheets("YOUR WORK SHEET")
'getting the total number of rows we may have to loop through to find the appropreate cell.
totalRow = ws.Range("C" & Rows.Count).End(xlUp).Row
'loops through the rows
For a = 1 To totalRow
'checks if the previous cell does not equal the current cell
If ws.Range("C" & a).Value <> ws.Range("C" & a - 1) Then
'if above statement is true, set the startSortRow to the value of a and exit the loop
startSortRow = a
Exit For
End If
Next
'Create the sort range string
sortRange = "A" & startSortRow & ":P100"
'Create the sort key
sortKey = "C" & startSortRow
'Sort based on the values found above
ws.Range(sortRange).Sort key1:=Range(sortKey), order1:=xlAccending, Header:=xlNo
End Sub
这应该可以在动态排序范围内正常工作。 (未经测试)