我正在处理一个项目,该项目的数据表包含10列和可变行数。第一栏' A'标题是"案例"并且此列中的输入未排序。我有专栏' X'其输入顺序正确。专栏' B'通过' J'基于列' A'。我正在寻找一种方法对列进行排序' A'基于专栏' X'。
输入如下所示:
C4
C1
C11
W36
W39
C21
它需要看起来像这样:
W36
W39
C1
C4
C11
C21
任何有关vba代码的帮助都会很有用。我对编程很新。
答案 0 :(得分:1)
您必须将表值带入数组,通过从A列中的数字字符(前者降序,后者升序)中分割字母字符来执行自定义内存中排序。
Sub sortVals()
Dim srt As Variant, tmp As Variant
Dim x As Long, a As Long, s As Long
With Worksheets("Sheet2")
With .Cells(1, 1).CurrentRegion
'grab values from primary key column
With .Resize(.Rows.Count - 1, 10).Offset(1, 0)
srt = .Cells.Value2
End With
'perform custom sort on array
For s = LBound(srt, 1) + 1 To UBound(srt, 1)
For a = LBound(srt, 1) To UBound(srt, 1)
If Asc(srt(s, 1)) > Asc(srt(a, 1)) Or _
Int(Mid(srt(s, 1), 2)) < Int(Mid(srt(a, 1), 2)) Then
ReDim tmp(1 To 1, LBound(srt, 2) To UBound(srt, 2))
For x = LBound(tmp, 2) To UBound(tmp, 2)
tmp(1, x) = srt(a, x)
srt(a, x) = srt(s, x)
srt(s, x) = tmp(1, x)
Next x
End If
Next a
Next s
'dump the values back into the worksheet
With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
.Cells(1).Resize(UBound(srt, 1), UBound(srt, 2)) = srt
End With
End With
End With
End Sub
答案 1 :(得分:0)
试试这个:
Sub SortData()
Range("A:X").Select 'Your Data range
ActiveWorkbook.Worksheets("Your sheet name").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Your sheet name").Sort.SortFields.Add Key:=Range("Sorting range IE: X:X"), _
SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Your sheet name").Sort
.SetRange Range("A:X") 'Your data range
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
您需要用自己的范围替换范围。