如何基于一列对多个命名范围进行sorting?

我需要sorting多个命名的范围在一个Excel中已经命名的Data1,Data2,…

在每个指定的范围内,都有一个将用于sorting的单元格。 我的问题是我想命名的范围内的所有数据相应地移动到sorting的单元格。

根据图片,如果A列sorting,右侧的数据也向上移动。

我的文件的例子

假设你要sorting的是几行中重复的string,比如列A,行24-50都包含“file1”,那么你可以使用下面的代码来select包含指定列中的string的所有行。 从那里你可以应用你的sorting。

Private Sub Test1() Dim c As Range Dim d As Range Dim Fitem As String Dim FEndRange As Long Dim FStartRange As Long 'Search for the name of the header you want to base your range off of... With Worksheets("Sheet1").Range("A1").EntireRow Set c = .Find("HEADER", LookIn:=xlValues) End With With Worksheets("Sheet1").Range(c.Address).EntireColumn Set d = .Find("file1", LookIn:=xlValues) Set c = Worksheets("Sheet1").Cells(d.Row, c.Column) Fitem = c.Value End With If (c.EntireColumn.Find(what:=Fitem, lookat:=xlWhole, After:=Cells(2, c.Column)).Row) 0 Then FStartRange = c.EntireColumn.Find(what:=Fitem, After:=Cells(1, c.Column)).Row FEndRange = c.EntireColumn.Find(what:=Fitem, After:=Cells(1, c.Column), searchdirection:=xlPrevious).Row Worksheets("Sheet1").Cells(FStartRange, d.Column).Activate Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(FStartRange, d.Column), Worksheets("Sheet1").Cells(FEndRange, d.Column)).EntireRow.Select ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=c, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers With ActiveWorkbook.Worksheets("Sheet1").Sort 'place your sort criteria here End With End If End Sub 

基于你的图片和评论的新信息,下面的代码应该让你在你需要的地方。

 Option Explicit Private Sub Test() Dim x As Long Dim y As Long Dim s As Long Dim t As Long Dim ws As Worksheet Dim rng As Range Dim lastrow As Long lastrow = ActiveWorkbook.Worksheets("Sheet1").Cells(ActiveWorkbook.Worksheets("Sheet1").Rows.Count, "E").End(xlUp).Row Set ws = Worksheets("Sheet1") ws.Activate y = WorksheetFunction.CountIf(Range("A:A"), "Data*") s = 1 For x = 1 To y s = ws.Range("A:A").Find(what:="Data*", after:=Range("A" & s)).Row If x = y Then t = lastrow + 2 Else t = ws.Range("A:A").Find(what:="Data*", after:=Range("A" & s)).Row End If ws.Range(ws.Cells(s, 5), ws.Cells(t - 2, 17)).Select 'Add sort criteria here Next x End Sub 

我使用的字母是任意的,可以改成任何东西。