VBS将一列拆分为两列

时间:2014-04-09 04:17:08

标签: vbscript split two-columns

让我们举个例子,我有一个列充满了名字,每个名字都在一个单元格中。

    First_Name_1 Last_Name_1
    First_Name_2 Last_Name_2
    First_Name_3 Last_Name_4

名字和姓氏用空格分隔。 如何使用Visual Basic脚本将此列拆分为两列,以便我在一列中包含First_Name,在其旁边的列中包含Last_name?

已经尝试过此代码,但无法使其正常运行。

    objExcel.ActiveSheet.Columns(4).Select
    Do Until IsEmpty(ActiveCell)
    'Search for position of space within the cell
    SplitPoint = InStrRev(ActiveCell, " ", -1, vbTextCompare)
    'Put the last name in the column next to the source column
    ActiveCell.Offset(0, 1) = Trim(Left(ActiveCell, SplitPoint))
    'Replace the source column with the first name
    ActiveCell.Offset(0, 0) = Trim(Mid(ActiveCell, SplitPoint))
    Loop

提前致谢!

2 个答案:

答案 0 :(得分:0)

你没有移动到范围的下一个单元格......

添加:

ActiveCell.Offset(1,0)。激活

我会添加一些东西来检查双重空格(删除一个),没有空格和双重名称或缩写(Mary Lou Smith,John M. Lewis)。

答案 1 :(得分:0)

Excel有一个TextToColumns()功能,可以通过单个函数调用执行您正在寻找的功能。

objExcel.ActiveSheet.Columns(4).TextToColumns , , , , , , , True

显示的参数可能更有意义。您的数据以空格分隔,因此我们只需将第8个参数设置为True。其余部分可以省略以接受默认值。

objExcel.ActiveSheet.Columns(4).TextToColumns _
    , _        ' Destination (optional, defaults to source)
    , _        ' DataType (optional, defaults to xlDelimited)
    , _        ' TextQualifier (optional, defaults to xlTextQualifierDoubleQuote)
    , _        ' ConsecutiveDelimiter
    , _        ' Tab-delimited? (optional, defaults to False)
    , _        ' Semicolon-delimited? (optional, defaults to False)
    , _        ' Comma-delimited? (optional, defaults to False)
    True       ' Space-delimited?
相关问题