将列中的文本拆分为两个单独的列

时间:2013-12-17 15:52:32

标签: excel excel-vba split vba

我无法根据“ - ”将位置上的文本拆分为两个单独的列。代码需要遍历每一行并拆分单元格值。

代码:

'Split Location into 2 Columns
    txt = Sheet4.Cells(i, 10).Value
    Location = Split(txt, "-")

    For i = 2 To LastRow2
        For j = 0 To UBound(Location)
            Cells(1, j + 1).Value = Location(j)
        Next j
    Next i

样本表: enter image description here

2 个答案:

答案 0 :(得分:0)

我认为问题只是你放在循环之外的Sheet4.Cells(i, 10).Value。尝试这样的事情:

For i = 2 To LastRow2
    'Split Location into 2 Columns
    txt = Sheet4.Cells(i, 10).Value
    Location = Split(txt, "-")

    For j = 0 To UBound(Location)
        Cells(1, j + 1).Value = Location(j)
    Next j
Next i

答案 1 :(得分:0)

以下代码假设您要操作的数据位于活动工作表上,并且您希望将当前工作表上的数据拆分并将其放入K列。

我会使用TextToColumns而不是循环

Range("J2:J" & LastRow2).TextToColumns Destination:=Range("J2"), _
                                       OtherChar:="-", _
                                       FieldInfo:=Array(Array(1, 1), Array(2, 1))

如果你想使用一个循环你可以在循环中包含txt / location变量并使用i / j作为数据放置的偏移量

For i = 2 To LastRow2
    'Split Location into 2 Columns
    txt = Cells(i, 10).Value
    Location = Split(txt, "-")

    For j = 0 To UBound(Location)
        Cells(i, 10 + j).Value = Location(j)
    Next j
Next i
相关问题