如何使用列标题作为参考排序?

问题描述 投票:0回答:2

在VBA中是否有办法使用它的标题名称对列进行排序?由于列可能会定期更改,我无法引用列号对其进行排序,我需要使用列标题进行排序。例如,我在列C中有订单状态(列标题),我需要对此订单状态进行排序,而不是将其作为列C提及。

这是我到目前为止的代码:

'Sort the "Order Status(Column C)" 
'Clear out any previous Sorts that may be leftover
ws.Sort.SortFields.Clear

'range that includes all columns to sort
Set Rngsort = ws.UsedRange

'Columns with keys to sort
Set RngKey1 = ws.Range("C1")

'Perform the sort
With ws.Sort
    Rngsort.Sort Key1:=RngKey1, Order1:=xlAscending, header:=xlYes, _
    OrderCustom:=Application.CustomListCount + 1, MatchCase:=False, _
    Orientation:=xlSortColumns, DataOption1:=xlSortNormal
End With
excel vba excel-vba
2个回答
0
投票

OP在显示他当前的代码后编辑

你可以使用这个助手子:

Sub SortIt(rngToSort As Range, header As String)
    With rngToSort ' reference passed range to sort
        .Sort key1:=.Rows(1).Find(what:=header, LookIn:=xlValues, lookat:=xlWhole), _
              order1:=xlAscending, header:=xlYes ' sort it by its column whose header is the passed one
    End With
End Sub

您可以在当前代码中利用如下:

With ws ' reference your sheet
    .Sort.SortFields.Clear 'Clear out any referenced sheet previous "Sorts" that may be leftover
    SortIt .UsedRange, "status" 'Perform the sort on the referenced sheet used range
End With

0
投票

虽然我怀疑.Find效率更高,并且肯定有更少的代码,这很好,我有兴趣使用Application.Match进行游戏,所以写了以下内容,我欢迎反馈......

我基本上尝试匹配headerToFind的标题行中的usedRange字符串,如果没有找到,则使用错误处理,否则排序。

Option Explicit

Public Sub test()

    Const headerToFind As String = "Header2"

    Dim wbTarget As Workbook
    Dim ws As Worksheet

    Set wbTarget = ThisWorkbook
    Set ws = wbTarget.Worksheets("Sheet1")       'change as appropriate

    Dim RngSort As Range
    Dim sortField As Long

    Set RngSort = ws.UsedRange
    ws.Sort.SortFields.Clear

    On Error GoTo Errhand

    sortField = Application.Match(headerToFind, RngSort.Rows(1), 0)

    Dim RngKey1 As Range

    Set RngKey1 = RngSort.Rows(1).Cells(sortField)

    With ws.Sort

        RngSort.Sort Key1:=RngKey1, Order1:=xlAscending, Header:=xlYes, _
                     OrderCustom:=Application.CustomListCount + 1, MatchCase:=False, _
                     Orientation:=xlSortColumns, DataOption1:=xlSortNormal
    End With

Exit Sub

Errhand:

Select Case Err.Number

Case 13

    MsgBox "Header not found"

Case Else

    Debug.Print Err.Number & Err.Description

End Select

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.