将逗号分隔的值复制到两个新行中

时间:2013-09-16 14:57:47

标签: excel vba

我有2列,其中2列有几个用逗号分隔的数字,但我要做的是将这些数字分开并为每个数字插入新行。为了解释一下这里的内容是什么:

Current issue:
Code1   Code2
2510'   2512 '
0542','0740','5282','5280 '
38101'  3829 '
99812'  9981'

运行宏或VB代码后,我希望我的结果看起来像这样

Desired Results:
Code1   Code2
2510'   2512 '
0542'   5280 '
'0740'  5280 ' 
'5282'  5280 '
38101'  3829 '
99812'  9981'

这是我找到的解决方案:谢谢

Sub ExpandData()
    Const FirstRow = 2
    Dim LastRow As Long
    LastRow = Range("A" & CStr(Rows.Count)).End(xlUp).Row

    ' Get the values from the worksheet
    Dim SourceRange As Range
    Set SourceRange = Range("A" & CStr(FirstRow) & ":B" & CStr(LastRow))

    ' Get sourcerange values into an array
    Dim Vals() As Variant
    Vals = SourceRange.Value

    ' Loop through the rows in the array and split each comma-delimited list of items and put each on its own row
    Dim ArrIdx As Long
    Dim RowCount As Long
    For ArrIdx = LBound(Vals, 1) To UBound(Vals, 1)

        Dim CurrCat As String
        CurrCat = Vals(ArrIdx, 1)

        Dim CurrList As String
        CurrList = Replace(Vals(ArrIdx, 2), " ", "")

        Dim ListItems() As String
        ListItems = Split(CurrList, ",")

        Dim ListIdx As Integer
        For ListIdx = LBound(ListItems) To UBound(ListItems)

            Range("A" & CStr(FirstRow + RowCount)).Value = CurrCat
            Range("B" & CStr(FirstRow + RowCount)).Value = ListItems(ListIdx)
            RowCount = RowCount + 1

        Next ListIdx

    Next ArrIdx

End Sub

1 个答案:

答案 0 :(得分:0)

这是使用SPLIT功能的绝佳机会。这可以在VBA代码中使用,也可以用作工作表函数。

正如tigeravatar指出的那样,最好的办法就是自己动手。您可以查看this question。有关拆分功能的更多信息,请访问MS here