在Excel 2013中拆分数据

时间:2018-06-27 22:37:30

标签: excel excel-vba excel-formula vba

我对Excel宏非常陌生。我在Excel中有以下数据:

Col1 Col2       col3    col4  Col5
32    000-001                   1
32    002-001                   100
32    005-000                   20

,依此类推。我的Excel电子表格中有6313行。

我想拆分col2并将col3中的连字符前三个数字放在col3中,并将col3中的最后三个数字放入。我也想从col2中删除连字符,所以我的最终输出将如下所示:

col1   col2     col3    col4    col5
32    000001    000      001    1
32    002001    002      001    100
332   005000    005      000    20

这是我已经尝试过的。我试图用空格替换连字符,然后丢失所有前导零。我不想失去col2的所有前导零。

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:2)

尝试一下:

Sub aljali()
    Dim i As Long, N As Long

    Range("A:E").NumberFormat = "@"
    N = Cells(Rows.Count, "A").End(xlUp).Row

    For i = 1 To N
        Cells(i, "B").Value = Replace(Cells(i, "B").Value, "-", "")
        Cells(i, "C").Value = Left(Cells(i, "B").Value, 3)
        Cells(i, "D").Value = Right(Cells(i, "B").Value, 3)
    Next i
End Sub

注意:

关键是将单元格的格式设置为“ 文本”。这有助于保留那些前导零。

答案 1 :(得分:2)

假设Col1位于A1中:将ColumnB移至ColumnC,以-作为定界符将文本拆分为列(为两列均选择Text),然后在B2中复制并向下复制以适合:

=C2&D2

答案 2 :(得分:1)

尝试

With Worksheets("sheet8")
    For i = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
        With .Cells(i, "B")
            .Resize(1, 3).NumberFormat = "@"
            .Resize(1, 3) = Array(Replace(.Value2, Chr(45), vbNullString), _
                           Split(.Value2, Chr(45))(0), _
                           Split(.Value2, Chr(45))(1))
        End With
    Next i
End With

答案 3 :(得分:0)

如果可以选择在VBA之外执行此操作(标记为 Excel-Formula),则可以使用以下三个功能:LeftRight,和Substitute

您将需要添加一个额外的列以实现此目的。

enter image description here

这将产生以下结果:

enter image description here