我们假设一个简单的Excel电子表格,其中有两列A和B,其中B列中有逗号分隔值。 我需要一个VBA函数来分别从包含它们的单元格下面的行开始的新行中分割这些值。 这是一个例子:
PRE
Column A Column B
AAAAA this,is,a,test
BBBBB other,values
CCCCC 1,2,3,4
POST
Column A Column B
AAAAA
this
is
a
test
BBBBB
other
values
CCCCC
1
2
3
4
我发现这个问题帮了我:Split text in cells at line breaks 并以这种方式修改了它的解决方案:
Sub SplitIt()
ActiveSheet.Copy after:=Sheets(Sheets.count)
Dim tmpArr As Variant
Dim Cell As Range
For Each Cell In Range("B1", Range("B2").End(xlDown))
If InStr(1, Cell, ",") <> 0 Then
tmpArr = Split(Cell, ",")
Cell.Offset(1, 0).Resize(UBound(tmpArr), 1). _
EntireRow.Insert xlShiftDown
Cell.Resize(UBound(tmpArr) + 1, 1) = Application.Transpose(tmpArr)
End If
Next
Application.CutCopyMode = False
End Sub
但它不会向下移动B列的值。 有办法吗?
答案 0 :(得分:2)
已编辑,问题是B栏中值的转移
编辑2 来处理这样一个事实:在Excel 2016中,新添加的工作表似乎不会成为 Active 一个
已编辑3 以说明C列中的值
Sub SplitIt()
Dim tmpArr As Variant, vals As Variant
Dim iRow As Long
vals = Range("C1", Cells(Rows.Count, "A").End(xlUp)).value
With Worksheets.Add(after:=Sheets(Sheets.Count))
For iRow = LBound(vals) To UBound(vals)
tmpArr = VBA.Split(vals(iRow, 2), ",")
With .Cells(Rows.Count, "B").End(xlUp).Offset(1)
.Offset(, -1).value = vals(iRow, 1)
.Offset(1).Resize(UBound(tmpArr) + 1).value = Application.Transpose(tmpArr)
.Offset(, 1).value = vals(iRow, 3)
End With
Next
End With
End Sub