excel - 根据每个条目的最后两个字符使用 VBA 对表进行排序

标签 excel sorting vba

在列(“E”)中是:

BDB1-1
BDB1-2
.
.
.
BDB1-9
BDB1-10
BDB1-11

我喜欢对这一列进行排序。如果我使用常规 Sort 这样做,代码错误地列出了 BDB1-10BDB1-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/

相关文章:

excel - 27位二进制到十进制转换

excel - 如何在 Excel VBA 中将整数设为 null?

excel - 使用 Active.cell.column 和行范围的 VBA 范围

sorting - Elasticsearch 对字符串进行排序未返回预期结果

vba - Excel VBA - 在搜索框中输入的文本不会导致页面显示结果(搜索没有提交按钮)

vba - 仅在一张纸上运行 excel 宏

Java Jxl 读/写工作簿

excel - 基于列创建多行

c# - 合并列表和 "merge"排序

java - 自然排序和全排序的区别