Excel - 将值列表转换为范围

时间:2016-12-22 15:44:22

标签: excel list excel-vba range vba

如果可以在Excel中使用以下内容,请告诉我吗?

我有一个数字列表,即:

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

我希望以下列格式提供这些号码:

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

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

谢谢

中号

1 个答案:

答案 0 :(得分:1)

我们的想法是遍历数字,每个新数字都可以扩展当前范围或开始新的范围。一种可能的实现如下:

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