我正在努力弄清楚如何选择所有数据,并根据“服务凭单”的列标题名称进行排序。关于如何对“硬编码”列进行排序的例子很多。我的问题是,导入的数据表通常可能具有不同的列数,从而导致感兴趣的列发生更改。
答案 0 :(得分:1)
听起来像您已经发现VBA可以按给定列进行排序。使用Find
来找到您感兴趣的标题,然后将列号分配给一个变量,并使用该变量代替静态列引用。
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