0

我有一个包含 10 列的电子表格(A 列、B 列、...、J 列)。我正在尝试创建一个宏来根据第 1 行和第 3 行中的条目(首先按值排序第 1 行中的 A 到 Z,然后按第 3 行中的值 A 到 Z)。

如果我记录自己这样做,这很容易。但是,如果将来需要排序的列数发生变化(例如,如果添加了两个新列),则以这种方式记录的宏不再起作用。如何创建一个宏来对突出显示的列执行此排序?

谢谢

4

2 回答 2

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
于 2012-11-28T19:21:34.803 回答
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

这两个步骤在我的努力中对我很有用。继续搜索和学习!

于 2012-11-28T13:59:09.233 回答