我是 VBA 新手,遇到了这个问题。
表位置和值

A1 S+01a
A2 S+02a
A3 S+03a
A4 S-01a
A5 S-01b
A6 S-02a

由于这是由 VBA 生成的,我想按此顺序订购
A1 S+01a
A2 S-01a
A3 S-01b
A4 S+02a
A5 S-02b
A6 S+03a

排序规则将是
  • 加号
  • 后面的数字最小
  • 与加号相同数字的减号(如果存在)
  • (仅用于减号)最后一个字符的字母顺序

  • 我想通过 VBA 执行此操作(因为数据长度会更大)
    这种情况有什么线索吗?

    谢谢你的回答/线索。

    最佳答案

    由于我不确定您的代码如何处理数组(或集合)并且您没有向我展示实际代码,因此我编写了这个 POC,但它的编码很差。
    基本上,我对字符串进行编码解码,优先考虑您的排序标准(包括 + 和 - 符号)。

    Sub test()
    Dim array_unsorted(1 To 6) As String
    Dim i As Long
    
    Dim recoded(1 To 6) As String
    Dim temp As String
    Dim target As String
    
    array_unsorted(1) = "S+01a"
    array_unsorted(2) = "S+02a"
    array_unsorted(3) = "S+03a"
    array_unsorted(4) = "S-01a"
    array_unsorted(5) = "S-01b"
    array_unsorted(6) = "S-02a"
    
    For i = 1 To 6
        target = array_unsorted(i)
        temp = Replace(target, "+", "A")
        temp = Replace(target, "-", "Z")
        recoded(i) = Mid(temp, 3, 2) & Right(temp, 1) & target
    Next
    
    Call QuickSort(recoded, 1, 6)
       For i = 1 To 6
        s = Right(recoded(i), 5)
        Debug.Print s
        Next
    End Sub
    
    
    Public Sub QuickSort(ByRef vArray As Variant, inLow As Long, inHi As Long)
    
      Dim pivot   As Variant
      Dim tmpSwap As Variant
      Dim tmpLow  As Long
      Dim tmpHi   As Long
    
      tmpLow = inLow
      tmpHi = inHi
    
      pivot = vArray((inLow + inHi) \ 2)
    
      While (tmpLow <= tmpHi)
    
         While (vArray(tmpLow) < pivot And tmpLow < inHi)
            tmpLow = tmpLow + 1
         Wend
    
         While (pivot < vArray(tmpHi) And tmpHi > inLow)
            tmpHi = tmpHi - 1
         Wend
    
         If (tmpLow <= tmpHi) Then
            tmpSwap = vArray(tmpLow)
            vArray(tmpLow) = vArray(tmpHi)
            vArray(tmpHi) = tmpSwap
            tmpLow = tmpLow + 1
            tmpHi = tmpHi - 1
         End If
    
      Wend
    
      If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
      If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi
    
    End Sub
    

    至少它有效并且可以作为一个起点。快乐编码。
    干杯!

    关于自定义顺序的 Excel VBA 排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52380844/

    10-16 01:55