宏用于将用逗号分隔的数字拆分为不同单元格中的单独数字

时间:2016-07-10 18:09:41

标签: excel vba excel-vba split

所以我在excel中有一串数字,每个数字都是1-2位,但用逗号分隔,可以有不同数量的数字。例如: 例如:

       A            B               C 
9, 13, 42, 44  |  1, 18  |  24, 30, 61, 23, 30

我想要一个宏,它接受每一行(例如9,13,42,44)并将每个数字i放在同一列中的不同单元格中 - 就像这样

9
13
42
44

3 个答案:

答案 0 :(得分:2)

选择您要处理的单元格并运行此短宏:

Sub SplitThem()
    Dim r As Range
    For Each r In Selection
        ary = Split(Replace(r.Value, " ", ""), ",")
        i = 1
        For Each a In ary
            r.Offset(i, 0).Value = a
            i = i + 1
        Next a
    Next r
End Sub

enter image description here

每个项目与其父列表位于同一列。

答案 1 :(得分:2)

如果你想保持"原创"值:

Option Explicit

Sub SplitNumbers()
    Dim cell As Range
    For Each cell In Worksheets("mySheet").Rows(1).SpecialCells(xlCellTypeConstants) '<--| choose your row of interest
        cell.Offset(1).Resize(UBound(Split(cell.Value, ", ")) + 1) = Application.Transpose(Split(cell.Value, ", "))
    Next cell
End Sub

如果你想删除&#34;原创&#34;值:

Option Explicit    

Sub SplitNumbers2()
    Dim cell As Range
    For Each cell In Worksheets("mySheet").Rows(1).SpecialCells(xlCellTypeConstants) '<--| choose your row of interest
        cell.Resize(UBound(Split(cell.Value, ", ")) + 1) = Application.Transpose(Split(cell.Value, ", "))
    Next cell
End Sub

答案 2 :(得分:1)

将数据放在第一行的一系列单元格中,

split_transpose
splitTranspose子程序之前的数据

运行此快速子程序,该程序使用VBA的Split function和工作表的TRANSPOSE function

Sub splitTranspose()
    Dim c As Long, vals As Variant
    With Worksheets("Sheet1")
        For c = 1 To .Cells(1, .Columns.Count).End(xlToLeft).Column
            If CBool(InStr(1, .Cells(1, c).Value2, Chr(44))) Then
                vals = Split(Replace(.Cells(1, c).Value2, Chr(32), vbNullString), Chr(44))
                .Cells(1, c).Resize(UBound(vals) + 1, 1) = _
                  Application.Transpose(vals)
            End If
        Next c
    End With
End Sub

您的结果应类似于以下内容,

split_transpose_after
splitTranspose子程序之后的数据