繁体   English   中英

Excel - 将值列表转换为范围

[英]Excel - Convert list of values into ranges

您能否让我知道以下在 Excel 中是否可行?

我有一个数字列表,即:

1
2
3
4
6
7
8
9
11
14
16
17
18

我希望这些数字采用以下格式:

1-4, 6-9, 11, 14, 16-18

如果可能或您有任何问题,请告诉我。

谢谢

这个想法是遍历数字,每个新数字要么扩展当前范围,要么开始一个新范围。 一种可能的实现如下:

Sub GroupInRanges():
    Dim S As Range, R As Range
    Dim i As Long, j As Long, n As Long
    Dim num As Long, startNum As Long, endNum As Long

    Set S = Application.InputBox("Select range containing numbers", Type:=8)
    Set R = Application.InputBox("Select first cell of output range", Type:=8)
    n = S.Cells.Count

    startNum = S.Cells(1).Value
    endNum = startNum
    For i = 1 To n
        num = S.Cells(i).Value
        If num <= endNum + 1 Then
            'extend current number range
            endNum = num
        Else
            'process the just-completed data range
            R.Offset(j).Value = IIf(startNum < endNum, startNum & "-" & endNum, endNum)
            j = j + 1
            startNum = num 'starts a new number range
            endNum = startNum
        End If
    Next i

    'process final range
    R.Offset(j).Value = IIf(startNum < endNum, startNum & "-" & endNum, endNum)
End Sub

目标范围内的单元格应设置为文本格式,否则 Excel 会将1-4解释为4-Jan

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM