在列(“E”)中是:
BDB1-1
BDB1-2
.
.
.
BDB1-9
BDB1-10
BDB1-11
我喜欢对这一列进行排序。如果我使用常规
Sort
这样做,代码错误地列出了 BDB1-10
在 BDB1-2
之前入口:With Sheets("Probeninventar")
.Range("A8:Z" & LastRow + 1).Sort key1:=.Range("E8"), order1:=xlAscending
End With
我怎样才能以一种简洁的方式避免这种情况?
最佳答案
您可以稍微“作弊”,在您的范围右侧添加一个帮助列,在其中仅添加正确的 2 个数字作为字符串,根据它进行排序,最后将其删除。
代码
Option Explicit
Sub AddHelperColumn()
Dim LastRow As Long, i As Long
With Sheets("Probeninventar")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range("AA8:AA" & LastRow).NumberFormat = "@" ' format the helper column as Text
For i = 8 To LastRow
If Int(Mid(.Range("E" & i).Value, InStr(.Range("E" & i).Value, "-") + 1)) < 10 Then
.Range("AA" & i).Value2 = "0" & CStr(Mid(.Range("E" & i).Value, InStr(.Range("E" & i).Value, "-") + 1)) ' if less then 10, add `0` as prefix
Else
.Range("AA" & i).Value2 = CStr(Mid(.Range("E" & i).Value, InStr(.Range("E" & i).Value, "-") + 1))
End If
Next i
.Range("A8:AA8" & LastRow + 1).Sort key1:=.Range("AA8"), order1:=xlAscending ' sort according to "helper" column
.Columns(27).Delete ' delete the "helper" column
End With
End Sub
关于excel - 根据每个条目的最后两个字符使用 VBA 对表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49728666/