将单元格中的值范围转换为逗号分隔列表

时间:2016-06-21 05:35:56

标签: excel excel-vba excel-formula vba

我是否可以在单元格B1中查看A1并创建基于逗号的列表?

下面,A1是我可以输入的内容。 B1是一个公式。这可能吗?我将使A1始终遵循与XXX-XXX范围相同的格式。

+-------+-----------+----------------------+
| TABLE | A (Input) |      B (Result)      |
+-------+-----------+----------------------+
|     1 | 1-10      | 1,2,3,4,5,6,7,8,9,10 |
+-------+-----------+----------------------+

2 个答案:

答案 0 :(得分:2)

将下面的代码放在常规VBA模块中,然后您可以使用(例如):

=NumRange(A1)
B1中的

Function NumRange(v)
    Dim arr, x As Long, rv As String, sep As String
    If InStr(v, "-") Then
        arr = Split(v, "-")
        arr(0) = Trim(arr(0))
        arr(1) = Trim(arr(1))
        If IsNumeric(arr(0)) And IsNumeric(arr(1)) Then
            For x = CLng(arr(0)) To CLng(arr(1))
                rv = rv & sep & x
                sep = ","
            Next x
        End If
    End If
    NumRange = rv
End Function

编辑 - 处理多个范围

Function NumRange(v)
    Dim arrC, arr, x As Long, rv As String, sep As String, e

    arrC = Split(v, ",")
    rv = ""

    For Each e In arrC
        If InStr(e, "-") Then
            arr = Split(e, "-")
            arr(0) = Trim(arr(0))
            arr(1) = Trim(arr(1))
            If IsNumeric(arr(0)) And IsNumeric(arr(1)) Then
                For x = CLng(arr(0)) To CLng(arr(1))
                    rv = rv & sep & x
                    sep = ","
                Next x
            End If
        ElseIf IsNumeric(e) Then
            rv = rv & sep & CLng(e)
            sep = ","
        End If
    Next e
    NumRange = rv
End Function

答案 1 :(得分:1)

另一种UDF方法

=Spliced(A1)

中的

B1

Function Spliced(strIn As String) As String
X = Split(strIn, "-")
Spliced = Join(Application.Transpose(Evaluate("=ROW(A" & X(0) & ":A" & X(1) & ")")), ",")
End Function