【问题标题】:How to custom sort strings and numbers in VBA如何在 VBA 中自定义排序字符串和数字
【发布时间】:2020-04-27 11:13:59
【问题描述】:

我正在尝试对我的 Excel 电子表格中包含数字、字符串和“空”的列进行排序。我的目标是对数字进行降序排序,然后是空的,然后是字符串降序。

4 行的示例数据如下表所示。

Columns("A:A").Sort key1:=Range("A2"), order1:=xlDescending

通过正常的列排序,我可以按正确的顺序获取数字和“空”(失败代码)。但是,在降序排序时,字符串一直出现在数字之前。

     Initial    Failed_Code  Desired_Output

1    6566       String       6566
2               6566         700
3    700        700          
4    String                  String

【问题讨论】:

  • 我认为您需要 1) 进行排序 (Failed_Code),然后 2) 找到这三个组的边界,以及 3) 移动这些组。
  • 您可以添加一个辅助列,例如 =IF(ISNUMBER(A1),RANK(A1,$A$1:$A$4,1),IF(ISBLANK(A1),-1,-2)) 并按降序对该列进行排序。 (A1:A4 中的数据,在辅助列中填写)

标签: excel vba


【解决方案1】:

通常您可以在列表中指定排序顺序并使用 VBA 排序的OrderCustom 参数,例如在Code an Excel VBA sort with a custom order and a value containing commas 接受的答案中。但是,当您对整数和字符串进行排序时,通常建议的 helper/auxiliary 列 (Custom sort in Excel by first character and user-defined non-alphabetical order., ) 在这里也是一个更简单的解决方案,尤其是在自定义列表中 no wildcards 是可能(https://www.mrexcel.com/board/threads/custom-sort.471612/)。

! 是 ASCII 表和 Windows 排序顺序 (What is the first character in the sort order used by Windows Explorer?) 中控制字符之后的第一个字符,因此编写一个宏,根据要排序的单元格中的第一个字符创建辅助列 (@987654325 @),如果第一个字符是一个字母,前面加上!,则按辅助列降序排序。

另一种可能是最简单的解决方案,在您的情况下,首先对整个列升序进行排序,然后确定整数和之间的“边界”所在的索引通过检查第一个字符 (How to check first character in a cell value) 和然后分别对整数和字符串进行排序 降序,因为您始终可以指定排序范围,而不必一定排序tte 整列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    相关资源
    最近更新 更多