在VBA中对字符串变量进行排序

时间:2014-12-10 10:45:10

标签: excel vba excel-vba

我有四个字符串。这四个代表了四个季度。 这四个字符串是:(根据我的计算机实际上是排序顺序)。 这在弦乐世界中理论上是正确的。 Q1FY15 Q2FY15 Q3FY14 Q4FY14。

但如果我考虑年份部分,那么在按递增顺序排序之后我希望结果为

Q3FY14 Q4FY14 Q1FY15 Q2FY15

有人可以告诉我这是否可行而不考虑子串并发症:)

2 个答案:

答案 0 :(得分:0)

不是没有子串。你可以组合一个参考列= right(quartercell,2)& = left(quartercell,2),但这些是子字符串函数,但它们不使用术语substring

答案 1 :(得分:0)

如果您可以使用代码,则可以使用以下子代码对您的信息进行排序:

Option Explicit

Sub SortStrings()
'This sub will sort the values in column 1 by year and then by quarter based on
'the format of "Q1FY14"
'
'Written by TheEngineer on 12/10/2014

Dim LastRow As Long
Dim qCount  As Long
Dim i As Long, j As Long, k As Long

Application.ScreenUpdating = False

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

    For i = 1 To LastRow
        For j = i + 1 To LastRow
            If CInt(Right(.Cells(j, 1).Value, 2)) > CInt(Right(.Cells(i, 1).Value, 2)) Then
                If j <> i + 1 Then
                    .Cells(j, 1).Cut
                    .Cells(i + 1, 1).Insert Shift:=xlDown
                End If
            Else
                .Cells(j, 1).Cut
                .Cells(i, 1).Insert Shift:=xlDown
            End If
        Next j
    Next i

    qCount = 0
    For i = 1 To LastRow
        For j = i + 1 To LastRow
            If CInt(Right(.Cells(j, 1).Value, 2)) = CInt(Right(.Cells(i, 1).Value, 2)) Then
                qCount = qCount + 1
            End If
        Next j

        For k = i + 1 To qCount + i
            If CInt(Left(Right(.Cells(k, 1).Value, Len(.Cells(k, 1).Value) - 1), 1)) > CInt(Left(Right(.Cells(i, 1).Value, Len(.Cells(i, 1).Value) - 1), 1)) Then
                If k <> i + 1 Then
                    .Cells(k, 1).Cut
                    .Cells(i + 1, 1).Insert Shift:=xlDown
                End If
            Else
                .Cells(k, 1).Cut
                .Cells(i, 1).Insert Shift:=xlDown
            End If
        Next k
    qCount = 0
    Next i
End With

Application.ScreenUpdating = True

End Sub

请注意,此子信息假定您的信息位于第1列,并且只有您要排序的信息位于该列中。

这将适用于您需要的任意数量的字符串。