【问题标题】:Sort Blank cells to bottom in a descending sort using VBA使用 VBA 将空白单元格按降序排序到底部
【发布时间】:2020-04-24 17:51:39
【问题描述】:

我正在以降序对以下列进行独立排序,即每列中的最大值将始终位于顶行。但是,我在表格中有几个空白单元格。

这些实际上并不是空白,而是索引/匹配公式引用了另一个公式单元格IFERROR(H2/I2,""),它给出了一个空白答案。我希望在执行降序时对每列底部的空白单元格进行排序。

如何修改以下 VBA 代码以实现这一点?我希望解决方案更通用,并注意我按降序对填充单元格中的正数和负数进行排序的情况。

Sub SortIndividualCol()
    Dim xRg As Range
    Dim yRg As Range
    Dim ws As Worksheet
    Set ws = ActiveSheet
    On Error Resume Next
    Set xRg = Application.InputBox(Prompt:="Range Selection:", _
                                    Title:="Input header range", Type:=8)
    Application.ScreenUpdating = False
    For Each yRg In xRg
        With ws.Sort
            .SortFields.Clear
            .SortFields.Add Key:=yRg, Order:=xlDescending
            .SetRange ws.Range(yRg, yRg.End(xlDown))
            .Header = xlYes
            .MatchCase = False
            .Apply
        End With
    Next yRg
    Application.ScreenUpdating = True

排序前:

降序排序后,空白单元格排在最前面:

【问题讨论】:

  • 您愿意使用包含公式的辅助列吗?
  • 嗨@braX,是的,如果可以解决排序问题,我不介意添加新列。另一个限制是我更喜欢一个更通用的解决方案来处理这种情况,即我按降序对负数和正数进行排序。我在我的问题中编辑了这个

标签: excel vba sorting excel-formula


【解决方案1】:

这是一个基本循环,它将独立循环和排序每一列。 免责声明不会维护行数据的完整性。

For x = 1 To 5 'adjust to the number of columns you want to sort
    With ActiveSheet.Sort 'I prefer to use the actual sheet name
        .SortFields.Clear
        .SortFields.Add .Parent.Columns(x), Order:=xlDescending
        .SetRange .SetRange .Parent.Cells(1, x).Resize(6) 'you can use a last row variable -1
        .Apply
    End With
Next x

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    相关资源
    最近更新 更多