对具有多个小数的列进行排序

时间:2017-09-12 07:34:08

标签: excel vba excel-vba

我正在尝试在Excel工作表中对列A值进行排序。 例如:

1.2
2.1
3.1
1.1.1
1.2.3

当我点击排序按钮时,它应该重新排列。

1.2
1.1.1
1.2.3
2.1
3.1

我编写了一个排序代码,但代码只对单个十进制值进行排序,因为当我们添加多个点时它的整数然后excel转换它有String。你能告诉我哪里错了。

Private Sub Sort_Click()
    Dim xlSortA As XlSortOrder
    Dim LastRow As Long

    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        If (CInt(.Range("A2").Value) > CInt(.Range("A" & CStr(LastRow)))) Then
            xlSortA = xlAscending
        End If

        .Range("A2:D10" & LastRow).Sort Key1:=.Range("A2:D10"), Order1:=xlSort, Header:=xlNo, _
            OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
            DataOption1:=xlSortNormal
     End With

     ActiveWorkbook.Save
  End Sub

注意:根据排序,它必须重新排列剩余的列,并且正在运行。

1 个答案:

答案 0 :(得分:0)

分割后的数据' 1.2.3'用"。" ,并使用新工作表中的三列对数据进行排序。

Sub test()
    Dim vDB, rngDB As Range
    Dim Ws As Worksheet, Temp As Worksheet
    Dim vSplit, vR(), v
    Dim r As Long, c As Integer, i As Long, n As Integer

    Set Ws = ActiveSheet
    With Ws
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        Set rngDB = .Range("a2", "d" & LastRow)
        vDB = rngDB
        r = UBound(vDB, 1)
        c = UBound(vDB, 2)
    End With
    ReDim vR(1 To r, 1 To 3)
    Set Temp = Sheets.Add
    With Temp
        .Range("a1").Resize(r, c) = vDB
        For i = 1 To r
            n = 0
            vSplit = Split(vDB(i, 1), ".")
            For Each v In vSplit
                n = n + 1
                vR(i, n) = v
            Next v
        Next i
        .Range("e1").Resize(r, 3) = vR
        .Range("a1").CurrentRegion.Sort Key1:=.Range("e1"), Order1:=xlAscending, key2:=.Range("f1"), Order2:=xlAscending, Key3:=.Range("g1"), order3:=xlAscending
        vDB = .Range("a1").Resize(r, c)
        Application.DisplayAlerts = False
        .Delete
        Application.DisplayAlerts = True
    End With
    rngDB = vDB
End Sub