我有一个包含10列的电子表格(A列,B列,......,J列)。我正在尝试根据第1行和第3行中的条目创建一个宏来对这些列进行排序(即最终得到类似于列B,列D,列A,......,列E的内容)(首先按值排序第1行中的A到Z,然后是第3行中的值A到Z.
如果我记录下自己这样做,这很容易。但是,如果将来需要订购的列数发生变化(例如,如果添加了两个新列),以这种方式记录的宏将不再有效。如何创建一个将在突出显示的列上执行此排序的宏?
由于
答案 0 :(得分:0)
虽然我同意之前发布的评论,但这对您的成长有一点鼓励。 代码删除已知的标题名称
' Delete Extranious Rows based on header name
Dim cellcolumn As Integer
' Replace each name in "" with the names of headers you do want
For Each b In Array("Unit Type", "Unit Profile", "Drop Profile", "Delivery Type", "Activity Time", "Miles")
On Error Resume Next
rng1 = b
strSearch = rng1
Set aCell = Sheets("Sheet1").Rows(1).Find(What:=strSearch, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, _
SearchFormat:=False)
cellcolumn = aCell.Column
Columns(cellcolumn).EntireColumn.Select
Selection.Intert Shift:=xlToRight
Next b
您尝试完成的任务可以通过多种方式完成。此方法将删除极端信息。当您知道要移动的内容和位置时,下一部分会组织信息。
Sub Organize()
' Organize Trip Stat
Dim Heder(1 To 5) As String
Heder(1) = "trip_id"
Heder(2) = "driver_id"
Heder(3) = "route_nbr"
Heder(4) = "trailer_id"
Heder(5) = "trip_type_code"
For a = 1 To 5
Call Organize(Heder(a))
Next a
End Sub
调用下一个代码来完成该过程
Function Organize(TheHeder)
For b = 1 To 50
If Cells(1, b).Text = TheHeder Then
Cells(1, b).EntireColumn.Select
If Range("B1").Text = TheHeder Then GoTo nextstep:
Selection.Cut
Columns(2).Select
Selection.Insert (xlToRight)
End If
Next b
nextstep:
End Function
这两个步骤在我的努力中对我有用。继续搜索和学习!
答案 1 :(得分:0)
Sub SortColumns()
Dim rngSort As Range
With ActiveSheet
Set rngSort = .Range("A1").CurrentRegion
With .Sort.SortFields
.Clear
.Add Key:=rngSort.Rows(1), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
.Add Key:=rngSort.Rows(3), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
End With
With .Sort
.SetRange rngSort
.Header = xlGuess
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
End With
End Sub