使用Excel拆分和排序字符串组件

时间:2013-04-30 09:12:11

标签: excel

我在Excel中有一列格式为:

A01G45B45D12

我需要一种方法来像这样格式化它,即将字符串分成三个字符的组,按字母顺序对组进行排序,然后将它们连接在一起,并在之间加上+号:

A01 + B45 + D12 + G45

我想知道这可以使用Excel中的内置公式,或者如果我必须使用VBA或其他东西这样做,我已经在C#中有了这个代码,如果有一种简单的方法可以从Excel中使用它。我之前没有为Excel编写插件。

编辑添加: 上面只是一个例子,字符串可以是“任意长度”,但它总是可以被3整除,顺序是随机的,所以我不能事先假定订单的任何内容。

1 个答案:

答案 0 :(得分:0)

Sub ArraySort()

Dim strStarter As String
Dim strFinish As String
Dim intHowMany As Integer
Dim intStartSlice As Integer

    strStarter = ActiveCell.Offset(0, -1).Value 'Pulls value from cell to the left

    intHowMany = Int(Len(strStarter) / 3)
    ReDim arrSlices(1 To intHowMany) As String


    intStartSlice = 1

    For x = 1 To intHowMany

        arrSlices(x) = Mid(strStarter, intStartSlice, 3)

        intStartSlice = intStartSlice + 3

    Next x

    Call BubbleSort(arrSlices)

    For x = 1 To intHowMany

        strFinish = strFinish + arrSlices(x) & "+"

    Next x


strFinish = Left(strFinish, Len(strFinish) - 1)
ActiveCell.Value = strFinish 'Puts result into activecell

End Sub


Sub BubbleSort(list() As String)
'Taken from power programming with VBA
'It’s a sorting procedure for 1-dimensional arrays named List
'The procedure takes each array element, if it is greater than the next element, the two elements swap positions.
'The evaluation is repeated for every pair of items (that is n-1 times)

    Dim First As Integer, Last As Long
    Dim i As Long, j As Long
    Dim temp As String
    First = LBound(list)
    Last = UBound(list)

    For i = First To Last - 1
        For j = i + 1 To Last
            If list(i) > list(j) Then
                temp = list(j)
                list(j) = list(i)
                list(i) = temp
            End If
        Next j
    Next i

End Sub