Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sorting 在单个单元格中对分隔字符串进行标记排序_Sorting_Excel_Vba - Fatal编程技术网

Sorting 在单个单元格中对分隔字符串进行标记排序

Sorting 在单个单元格中对分隔字符串进行标记排序,sorting,excel,vba,Sorting,Excel,Vba,我使用以下代码从数据验证单元中选择多个项。它可以工作,但我需要对单元格中的条目进行排序,这样无论用户从下拉列表中选择的顺序如何,结果都将是苹果、桔子、梨,而不是梨、苹果、桔子 这也将是很好的(但没有必要检查重复。谢谢你的帮助!急需 Option Explicit ' Developed by Contextures Inc. Private Sub Worksheet_Change(ByVal Target As Range) Dim rngDV As Range Dim oldVal As S

我使用以下代码从数据验证单元中选择多个项。它可以工作,但我需要对单元格中的条目进行排序,这样无论用户从下拉列表中选择的顺序如何,结果都将是苹果、桔子、梨,而不是梨、苹果、桔子

这也将是很好的(但没有必要检查重复。谢谢你的帮助!急需

Option Explicit
' Developed by Contextures Inc.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
If Target.Count > 1 Then GoTo exitHandler

On Error Resume Next
Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation)
On Error GoTo exitHandler

If rngDV Is Nothing Then GoTo exitHandler

If Intersect(Target, rngDV) Is Nothing Then
   'do nothing
Else
  Application.EnableEvents = False
  newVal = Target.Value
  Application.Undo
  oldVal = Target.Value
  Target.Value = newVal
  If Target.Column = 3 Then
    If oldVal = "" Then
      'do nothing
      Else
      If newVal = "" Then
      'do nothing
      Else
      Target.Value = oldVal _
        & ", " & newVal
      End If
    End If
  End If
End If

exitHandler:
  Application.EnableEvents = True
End Sub

不必使用各种排序算法,您可以临时将值存储在工作表上的某个范围内,然后使用该范围,在代码中使用
[range].sort()
函数对该范围进行排序。排序后,您可以将其读回
目标.Value
单元格,并在执行时对其进行分隔


若要删除重复项,请在对范围进行排序后,但在将其读回目标值之前,遍历范围中的每个单元格,如果单元格与下面的单元格相等,则删除并上移这些值。

您可以将oldVal拆分为数组,找到将newVal插入适当位置的位置,然后加入将数组还原为字符串。