excel:我如何在单元格内sorting?

我有一个逗号分隔的string,有可能使用Excel公式sorting单元格内的值?

这里有一个解决scheme(从这里偷走的快速代码)。 您只需将一个button连接到SortValsmacros,您可以单击该button,它将在活动单元格中对逗号分隔值进行sorting。

 Option Explicit Public Sub SortVals() Dim i As Integer Dim arr As Variant arr = Split(ActiveCell.Text, ",") ' trim values so sort will work properly For i = LBound(arr) To UBound(arr) arr(i) = Trim(arr(i)) Next i ' sort QuickSort arr, LBound(arr), UBound(arr) ' load sorted values back to cell Dim comma As String comma = "" ActiveCell = "" For i = LBound(arr) To UBound(arr) ActiveCell = ActiveCell & comma & CStr(arr(i)) comma = "," Next i End Sub Public Sub QuickSort(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 

您必须拆分string,对值sorting并从sorting的值中创build一个新的string。

当时这个问题被问到我的LAselect框架加载项是不是公众可以得到的。 但现在它是,它以优雅的方式解决了这些问题。

您只需在VBA中提供几行“解决scheme”代码,即可对您想要的任何东西进行sorting或sorting。

用逗号分隔的值使用VBA的Split()函数。 然后,您将拥有与您的单元格一样多的单独值; 如果splitvalues(1)是firstname,并且splitvalues(0)是lastname,则加载项可以按如下方式对单个单元格进行sorting:

 Dim splitvalues1 as Variant, splitvalues2 as Variant While LAselect(ControlSignal, BreakOutBox) valcol = BreakOutBox.Pins.ColData splitvalues1 = Split(BreakOutBox.Data.VBArray(BreakOutBox.Pins.RowSource, valcol), ",") splitvalues2 = Split(BreakOutBox.Data.VBArray(BreakOutBox.Pins.RowDestin, valcol), ",") If splitvalues1(0) > splitvalues2(0) Then ControlSignal = LA_ISLARGER ElseIf splitvalues1(0) < splitvalues2(0) Then ControlSignal = LA_ISSMALLER Else ControlSignal = LA_ISEQUAL End If Wend 

在LA_ISEQUAL,你将不得不testingsplitvalues1(1)等进一步排名重复名字上的姓氏。

是不是已经变得很清楚了,对于我的外接程序来说,插入一个单元格的多less分隔符字段,甚至包含哪些其他单元格,并不重要。 完整的logging都传递给你的“解决scheme”代码,你将有充分的自由,你想要sorting的属性。

我的演示可以从www.liquorice-allsorts.com获得,所以你可以试试看。