如何对一列变量名称进行升序和降序交替排序?

如何对一列变量名称进行升序和降序交替排序?

每当数据集中某一列的变量发生变化时,我都希望将排序从升序切换为降序。下面是一个演示我想要的排序的示例。我尝试添加另一列以添加奇数或偶数,然后当偶数时按升序排序,当奇数时按降序排序,但不知道如何让它工作。我如何通过宏交替对这些变量进行排序,因为对于大型数据集,无法手动执行此操作?

ID  Sales
Apple   10
Apple   2
Apple   12
Orange      15
Orange      4
Guava   2
Guava   18
Guava   20
Guava   3


ID  Sales
Apple   12
Apple   10
Apple   2
Orange      4
Orange      15
Guava   20
Guava   18
Guava   3
Guava   2

我发现了当变量改变时插入空白行的 VBA 代码。关联 可以修改这个来改变排序顺序吗?

    sub AddBlankRows()
'
dim iRow as integer, iCol as integer
dim oRng as range

set oRng=range("a1")

irow=oRng.row
icol=oRng.column

do 
'
if cells(irow+1, iCol)<>cells(irow,iCol) then
    cells(irow+1,iCol).entirerow.insert shift:=xldown
    irow=irow+2
else
    irow=irow+1
end if
'
loop while not cells (irow,iCol).text=""
'
end sub

答案1

此 VBA 代码要求输入数字(任何偶数为升序,奇数为降序)用Mod函数测试它并使用标题对数据“A1:B11”进行排序,您可以将其更改为您的实际数据(根据输入数字对第 1 列(A)升序排序,对第 2 列(B)升序或降序排序

Sub DataSort()  
    Dim theRange As Range 
    Dim rep As Variant 
    Set theRange = Range("A1:B11") 
    rep = InputBox("Enter a number to decide order") 
    If rep Mod 2 = 0 Then    
      With ActiveSheet
        .Sort.SortFields.Clear
        .Sort.SortFields.Add Key:=theRange.Columns(1).Cells, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Sort.SortFields.Add Key:=theRange.Columns(2).Cells, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With .Sort
            .SetRange theRange
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
     End With
    ElseIf rep Mod 2 = 1 Then
        With ActiveSheet
        .Sort.SortFields.Clear
        .Sort.SortFields.Add Key:=theRange.Columns(1).Cells, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Sort.SortFields.Add Key:=theRange.Columns(2).Cells, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
         With .Sort
            .SetRange theRange
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
         End With
        End With
    End If
End Sub

相关内容