0

I'm struggling to figure out how I can select all data, and sort based off of a column header name of "Service Ticket". There are plenty of examples on how to sort off of a "hard-coded" column. My issue is the imported data sheet often might have a different number of columns, causing the column of interest to change.

1 Answer 1

1

Sounds like you have already found VBA to sort by a given column. Use Find to locate the header you are interested in, then assign the column number to a variable and use that variable in place of a static column reference.

Sub SortSomeColumn()

    Dim SvcTicketRange As Range
    Dim SortColumn As Integer

    With MyWorksheet
    
        Set SvcTicketRange = .Rows(1).Find(What:="Service Ticket", After:=.Cells(1, 1), LookIn:=xlValues, _
            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
        
        If Not SvcTicketRange Is Nothing Then
            SortColumn = SvcTicketRange.Column
            
            .Sort.SortFields.Clear
            .Sort.SortFields.Add Key:=Range(.Cells(1, SortColumn), .Cells(100, SortColumn)), _
                SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
                
            With .Sort
                .SetRange Range("A1:E100")
                .Header = xlYes
                .MatchCase = False
                .Orientation = xlTopToBottom
                .SortMethod = xlPinYin
                .Apply
            End With
            
        Else
            'define what you want to do if the Service Ticket header is not found
            
        End If
        
    End With
    
End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

Awwh... Thank you! This makes sense. I'll give it a shot.
Good luck, and don't forget to accept the answer if it solves the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.